In the previous article "JS Array Learning: How to Splice All Elements and Return a String", we learned about the method of converting an array into a string. Friends in need can learn about it. ~
This article will talk about the iterative operation of arrays, and introduce two methods of calculating the sum of elements and linking values into strings.
Method 1. Use the forEach() method
The forEach() method is used to call each element of the array and pass the element to Callback.
Syntax:
array.forEach(funtion callbackfn(value, index, array), thisValue)
funtion callbackfn(value, index, array)
: Required parameters, specify the callback function, which can receive up to three parameters:
value: The value of the array element.
index: Numeric index of the array element.
array: Array object containing the element.
thisValue
: an omitted parameter, an object that can be referenced by this in the callback function. If thisArg is omitted, the value of this is undefined.
Let’s learn more about it through code examples:
Example 1: Output array elements
function f(value,index,array) { console.log("a[" + index + "] = " + value); } var a = ['a', 'b', 'c']; a.forEach(f);
Example 2: Accumulating and summing array values
var a = [10, 11, 12], sum = 0; function f(value) { sum += value; } a.forEach(f); console.log(sum);
##Example 3: Concatenating array values into a string
var a = ['ab', 'cd', 'ef'], str = ""; function f(value) { // str=str + value; str=str.concat(value); } a.forEach(f); console.log(str);
Method 2. Use the reduce() method
reduce() method can reduce all elements in the array Call the specified callback function. The return value of this callback function is the cumulative result, and this return value is provided as a parameter the next time the callback function is called. Syntax:
array.reduce(function callbackfn(previousValue, currentVaule, currentIndex, array), initialValue)
function callbackfn(previousValue, currentVaule, currentIndex, array): Required parameters, specify the callback function, at most Can receive 4 parameters:
initialValue: Omissible parameter, initial value passed to the function.
Example 1: Accumulate and sum array values
var a = [11, 12, 13], sum = 0; function f(pre,curr) { sum=pre+curr; return sum; } a.reduce(f); console.log(sum);
36
Example 2: Concatenate array values into a string
var a = [11, 12, 13], str = ''; function f(pre,curr) { str=pre+''+curr; return str; } a.reduce(f); console.log(str);
var a = [11, 12, 13], str = ''; function f(pre,curr) { str=pre+'-'+curr; return str; } a.reduce(f); console.log(str);
The above is the detailed content of JS array learning: iterate through arrays, calculate the sum of elements, and concatenate values into strings. For more information, please follow other related articles on the PHP Chinese website!