首页 > 技术文章 > js——数组/对象常用方法总结

linjiangxian 2020-08-20 10:55 原文

 参考:http://www.mamicode.com/info-detail-2653981.html

   https://blog.csdn.net/w390058785/article/details/80522383

 

1. filter

  filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

  注意: filter() 不会对空数组进行检测。

  注意: filter() 不会改变原始数组。

  语法: 

array.filter(function(currentValue,index,arr), thisValue)

  参数:

  

 

 

 

  例:

  

let ages = [32, 33, 16, 40];
let arr = ages.filter(item => {
    return item >= 18
});

console.log(arr); //[32,33,40]

 

2. map

  map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

  map() 方法按照原始数组元素顺序依次处理元素。

  注意: map() 不会对空数组进行检测。

  注意: map() 不会改变原始数组。

  语法:

array.map(function(currentValue,index,arr), thisValue)

  参数:

  

  

 

  例:

  

let ages = [{age:18,num:1}, {age:19,num:2}];
let arr = ages.map(item => {
   item.age
});

console.log(arr); //[18,19]

 

3. reduce

 

  reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

  reduce() 可以作为一个高阶函数,用于函数的 compose。

  注意: reduce() 对于空数组是不会执行回调函数的。

  语法: 

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

 

  参数:

  

 

  例:

let numbers = [65, 44, 12, 4];

let sum = numbers.reduce((cur, next) => {
   return cur+ next; 
},10);

console.log(sum); //135,初始值为10

 

4. forEach

  forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。

  注意: forEach() 对于空数组是不会执行回调函数的。

  语法:

array.forEach(function(currentValue, index, arr), thisValue)

  参数:

  

 

 

 

  例:

  

let numbers = [4, 9, 16, 25];
 
number.forEach(item => {
    console.log(item); 
})

// 结果:
// 4
// 9
// 16
// 25

 

 

5. for...in 与 for...of

 

  数组:

let arr=[1,2,3,4];
arr.name = '张三'; //自定义属性
for (let i in arr){ console.log(i); //0,1,2,3,name 拿到的是数组的下标,set 和 map生成的数组不能使用for in(没有下标) } for (let i of arr){ console.log(i); //1,2,3,4 拿到的是数组的元素,且不会遍历自定义属性 }

 

  对象:

let obj=[name:'张三',age:18];

for (let i in obj){
    console.log(i); //name,age 拿到的是对象的属性名
}

for (let i of arr){
    console.log(i); //报错,因为此对象不是可迭代对象,但set 和 map生成的对象可以
}

 

推荐阅读