Commonly used array functions (filter, map, forEach, find/findIndex)

Functions in arrays use

1, filter: filter

It is required to return the Boolean type, and you can pass 3 parameters, filter (item, index, arr) are (each value item in the array, the subscript index corresponding to each value, the entire array arr), and finally return a new array

var nums = [10, 5, 11, 100, 55]
//[10, 5, 11, 100, 55]
//10 => true => 会被放到newNums
//5 => false => 不会被放到newNums
//11 => false => 不会被放到newNums
//100 => true => 会被放到newNums
//55 => false => 不会被放到newNums
var newNums = nums.filter(function(item) {
  return item % 2 === 0     // 偶数
})
console.log(newNums)   //[10,100]

2. map: mapping 

Some changes can be made to the original array. Finally a new array will be returned

var nums = [10, 5, 11, 100, 55]
var newNums2 = nums.map(function(item) {
  return item * 10
})
console.log(newNums2)  //[100,50,110,1000,550]

3. forEach: iteration (equivalent to traversal), no return value

var nums = [10, 5, 11, 100, 55]
nums.forEach(function(item) {
  console.log(item)
})
//打印结果
//10 
//5 
//11
//100
//55

4. find: find the value of an object

findIndex finds the index value (subscript) corresponding to the value of an object

var friends = [
  { name: "why", age: 18 },
  { name: "kobe", age: 40 },
  { name: "james", age: 35 },
  { name: "curry", age: 30 },
];

var findFriend = friends.find(function (item) {
  return item.name === "james";
});
console.log(findFriend);  //{ name: 'james', age: 35 }

var friendIndex = friends.findIndex(function (item) {
  return item.name === "james";
});
console.log(friendIndex);  //2

5. reduce: accumulate

You can pass 2 parameters, reduce (prevValue, item), respectively (the value returned by the last call to this method previousValue, the value item passed in this time) , previousValue does not have the previous value at the first call, you can use it yourself Defined as 0 (initialValue)

// prevValue: 0, item: 10
// prevValue: 10, item: 5
// prevValue: 15, item: 11
var nums = [10, 5, 11, 100, 55]
var total = nums.reduce(function (prevValue, item) {
  return prevValue + item;
}, 0);
console.log(total);  //181

Guess you like

Origin blog.csdn.net/weixin_53737663/article/details/127019240