This is the 4th day of my participation in the August More Text Challenge

Arguments to a function

  • Now, I have a requirement that I write a method for the sum of 10 numbers.

The code is as follows:

function sum(a, b, c, d, e, f, g, h, i, j) {
  var total = a + b + c + d + e + f + g + h + i + j;
  return total;
}

sum(1.2.3.4.5.6.7.8.9.10);
Copy the code

Limitations of function parameters:

  1. Because parameters and arguments correspond one to one, if you want to pass as many arguments as you want, you have to set as many parameters as you want, which is inconvenient. Now it’s 10. If it’s 100, you have to set 100 parameters.
  2. If the number of arguments is not fixed, it may be 10, 2, or 100, so the parameter cannot be set.
  • Requirement 2: You need to write a method that can sum up any number of numbers.

Any number of arguments, the parameter is not fixed. Do how?

To address the limitations of the above parameters, browsers build a arguments object into the function;

Arguments: Arguments is called the built-in argument set. This object contains all arguments passed to a function when it is executed (built-in: functions have a built-in mechanism that exists whether or not you set parameters and whether or not you pass arguments).

Using the arguments:

function sum2(n, m) {
  console.log(n, m);
  console.log(arguments);

   argumentsIt is an array of classes (not an array, you can't use the methods in the array directly). Even if you set the parameter, what should the parameter be, butargumentsIt stores all the arguments that are passed in, soargumentsIt's called the argument set and we found that it has an index, it has length, and it worksforLoop through {0: 1.1: 2.2: 5.3: 7.4: 8
     length: 5.callee: Stores the current function itselfarguments.callee == sum2 -> true
    }



}

sum2(1.2.5.7.8);
Copy the code

ES6 An indefinite parameter

  • ES6 provides a function similar to arguments’ function — indefinite arguments
function sum(. arg) {... It's called the expansion operator and arg is a parameterconsole.log(arg); Arg is an array} sum(1.2.4.5.7);
Copy the code
  • Arguments and indeterminate arguments
  1. Arguments are functions that come naturally and do not need to be declared; undefined arguments need to be declared
  2. Arguments are arrays of classes and undefined arguments are arrays

Sum of any number:

Ideas:

  1. Since it is an arbitrary number, you should definitely use arguments for the function
  2. Arguments store all the arguments that need to be fetched one by one (iterated) and added to the base value
  3. Return the result

The basic version:

function sum3() {
   1.Set the initial valuevar total = 0;

   2.traversearguments
  for (var i = 0; i < arguments.length; i++) {var item = arguments[i];
    total += item;
  }
   3.Return the result of the calculationreturn total;
}

var result = sum3(1.2.4.5);
console.log(result);
Copy the code

In order to improve the robustness of the code, we need to determine if the argument we pass is a number. If it is not a number, we first convert it to a number, and then see if it is a valid number.

function sum4() {
   1.Set the initial valuevar total = 0;
   2.traverseargumentsObject, and pull out each itemfor (var i = 0; i < arguments.length; i++) {
     3.No matter what number you send in, do it oncevar item = Number(arguments[i]);
     4.Determine whether the result after conversion is the accumulation of significant digits, and skip the non-significant digits directlyif (!isNaN(item)) {if notNaNLet total += item total += item; }}return total;
}
console.log(sum4(10.'20'.'aa'));  30

Copy the code

2. Function expression

  • Function classification:
  1. Real-name function: having a function name
  2. Anonymous function: without a function name

2.1 Function expressions: Treat functions as event attributes assigned to variables or element objects. 2.2 Self-executing functions: Created and executed together

  • Function expression:
  1. Assign a function as a value to a variable or property of an object
var fn = function () {
  console.log(I'm a functional expression.); }; fn(); Fn is a variable name that represents the event property that a function assigns to the element object: obox.onclick =function () {}; Attribute values for common objects:var obj = {
  getName: function () {
    console.log('River Glaze') } } obj.getName(); Because obj.getName is a function, it can also be executedCopy the code
  1. Self-executing functions: Functions are defined and declared together

(function (i) {the first part is the function definitionconsole.log('I was', i); }) (10); The parentheses after the function are the ones that make the function executefunction (i) {
  console.log(i); } (10);

+function (i) {
  console.log(i); } (10);

!function (i) {
  console.log(i); } (10);
Copy the code

Third, function recursion

Functions: divided into the definition part and the execution part

Function recursion: Repeating the behavior by calling the function itself from within the function body.

  • Requirement: Write a method to find the sum of all numbers between 1 and 10
function rSum(num) {
  if (num === 10) {
    return 10
  }
  return num + rSum(num + 1If the return value of a function encounters an expression, the function waits for the expression to evaluate and then returns the value.return 1 + rSum(2)
   return 1 + 2 + rSum(3)
   return 1 + 2 + 3 + rSum(4)
   return 1 + 2 + 3 + 4 + rSum(5)
   return 1 + 2 + 3 + 4 + 5 + rSum(6)
   return 1 + 2 + 3 + 4 + 5 + 6 + rSum(7)
   return 1 + 2 + 3 + 4 + 5 + 6 + 7 + rSum(8)
   return 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + rSum(9)
   return 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + rSum(10)
   return 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
}
console.log(rSum(1));
Copy the code
  • Requirement: Find the sum of all numbers from 1 to 10 that are multiples of 3.
function rSum2(num) {
  if (num === 10) {
    return 0
  }
  if (num % 3= = =0) {
    return num + rSum2(num + 1)}else {
    return rSum2(num + 1);
  }
   return rSum2(2)
   return rSum2(3)
   return 3 + rSum2(4)
   return 3 + rSum2(5)
   return 3 + rSum2(6)
   return 3 + 6 + rSum2(7)
   return 3 + 6 + rSum2(8)
   return 3 + 6 + rSum2(9)
   return 3 + 6 + 9 + rSum(10)
   return 3 + 6 + 9 + 0
}
console.log(rSum2(1));
Copy the code

Note: Recursion, like for loops, is used with termination conditions in mind. Otherwise, an infinite loop will be created, causing stack overflow.

4, array common methods

I array deletion and append

  1. => push
  • Function: Appends items to end of array (multiple items can be separated by commas)
  • Parameter: The item to add to the array
  • Return value: The length after the append to the array
  • Whether the original array is changed: Yes
var ary1 = [1.2.3];
var r1 = ary1.push(4.5);
console.log(ary1, r1);
Copy the code
  1. => pop
  • Deletes an item at the end of an array
  • Parameters: no
  • Return value: The array item that was deleted
  • Whether the original array is changed: Yes
var ary2 = [1.2.4];
var r2 = ary2.pop();
console.log(ary2, r2);
Copy the code
  1. => unshift
  • Adds an item to the beginning of an array
  • Parameter: item to append to the beginning
  • Return value: The new length of the array after the append
  • Whether the original array is changed: Yes
var ary3 = [1.2.3];
var r3 = ary3.unshift(4.5);
console.log(ary3, r3);
Copy the code
  1. => shift
  • Deletes the start item of the array
  • Parameters: no
  • Return value: deleted item
  • Whether the original array is changed: Yes
var ary4 = [1.2.3];
var r4 = ary4.shift();
console.log(ary4, r4);
Copy the code
  1. => splice(n, m)
  • Function: Deletes m entries from the index n
  • Parameter: start index n, number to delete
  • Return value: A new array of deleted items
  • Whether the original array is changed: Yes
var ary5 = [1.2.3];
var r5 = ary.splice(1.2);
console.log(ary5, r5);
Copy the code
  1. => splice(n, m, x)
  • Delete m entries from index n and replace them with x
  • Parameters: initial index, number of deletions, array item x to replace
  • Return value: a new array of deleted items
  • Whether the original array is changed: Yes
var ary6 = [1, 2, 3];
var r6 = ary6.splice(1, 1, 5);
console.log(ary6, r6);

Copy the code
  1. => splice(n, 0, x)
  • Delete 0 from index n and insert x before n
  • Parameter: start index, delete number 0, x
  • Return value: an empty array
  • Whether the original array is changed: Yes
var r7 = ary.splice(1.0.5);
var ary7 = [1.2.3];
console.log(ary7, r7);

Copy the code

II. Array replication and splicing

  1. slice(n, m)
  • Copy from index n to index m (excluding m)
  • Parameters: start index n, end index m; Note: if m does not write, copy to the last item. If n and m do not write, copy from the beginning to the end
  • Return value: a new array of copied items
  • Whether the original array is changed: No
var ary8 = [1.2.4.5];
var r8 = ary8.slice(1.3);
var r9 = ary8.slice(1);
var r10 = ary8.slice();
var r11 = ary.slice(0);
console.log(r8);
console.log(r9);
console.log(r10);
console.log(r11);

Copy the code
  1. => concat()
  • Effect: Concatenates an array
  • Parameter: the array or item to concatenate
  • Return value: the new array after concatenation
  • Whether the original array is changed: No
var ary12 = [1.3.5.7];
var r12 = ary12.concat([9.11]); The argument is passed an arrayconsole.log(ary12, r12);

var r13 = ary12.concat(9.11); Parameter passes an array entryconsole.log(ary12, r13);

varr14 = ary12.concat(); Not passing an argument is equivalent to making a copy of the arrayconsole.log(r14);
console.log(r14 === ary12);  false

Copy the code

III. Array conversion to string

  1. => join()
  • Function: Concatenates an array into a string based on the delimiter specified by the argument
  • Parameter: delimiter, default empty string if not specified
  • Return value: concatenated string
  • Whether the original array is changed: No
var ary15 = [1.3.5.7];
var str15 = ary15.join('+');
console.log(ary15, str15);

Copy the code
  1. => toString()
  • Converts an array to a string
  • Parameters: no
  • Return value: a string
  • Whether the original array is changed: No
var ary16 = [1.2.5.8];
var str16 = ary16.toString();
console.log(ary16, str16);

Copy the code

IV whether the item appears in the array

  1. => indexOf(x)
  • Function: The index position of the first occurrence of the item x in the array
  • Parameter: array entry x
  • Return value: Returns the index of the first occurrence of the item if it exists in the array, or -1 if it does not
  • Whether the original array is changed: No
var ary17 = [1.3.5.7];
var r17 = ary17.indexOf(3);
console.log(ary17, r17);

var r18= ary17.indexOf('bingo');
console.log(ary17, r18);  -1
Copy the code
  1. => lastIndexOf(x)
  • Function: The index position of the last occurrence of the item x in the array
  • Parameter: array entry x
  • Return value: Returns the index of the item’s last occurrence if it exists in the array, or -1 if it does not
  • Whether the original array is changed: No
var ary19 = [1.3.5.7.3];
var r19 = ary19.lastIndexOf(3);
console.log(ary19, r19);

var r20 = ary19.lastIndexOf('bingo');
console.log(ary19, r20);  -1

Copy the code

V. Array sort and reverse order

  1. => sort(function (a, b) { return a – b

})

  • Function: To sort an array in ascending or descending order
  • Argument: callback function
  • Return value: If the callback function return a – b returns the ascending array
  • If the callback function return b-a returns the descending array;
  • Whether the original array is changed: Yes
var ary21 = [1.5.2.6.4];
var r21 = ary21.sort(function (a, b) {
  return a - b
});
var r22 = ary21.sort(function (a, b) {
  return b - a;
});
console.log(ary21, r21, r22);

Copy the code
  1. reverse()
  • Action: Inverts an array
  • Parameters: no
  • Return value: flipped array
  • Whether the original array is changed: Yes
var re = ary21.reverse();
console.log(ary21, re);

Copy the code

VI array traversal method (traversal: fetch each item in the array)

    1. forEach(function (item, index) {

    These values can be manipulated in the callback function

})

  • Function: Iterate over the number group
  • Parameter: callback function (callback function argument: item traverses each array item, index is the index of this array item)
  • Returned value: None
  • Whether the original array is changed: No
var ary23 = [1.2.5.7.9];

var r23 = ary23.forEach(function (item, index) {
  console.log(item, index);
});
console.log(ary23, r23);

Copy the code
  1. => map(function (item, index) {})
  • Effect: Maps an array to a new array
  • Parameters: callback function (callback function parameters are the same as forEach)
  • Return value: A new array of the return values of the callback function
  • Whether the original array is changed: No
var ary24 = [1.2.5];
var r24 = ary24.map(function (item, index) {
  return item  2;
});
console.log(ary24, r24);
Copy the code