filter() 方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。
const words = ['active', 'sunlight', 'self-confident', 'clever', 'health'];
const result = words.filter((word) => word.length == 6);
console.log(result);
结果如下:
> Array ["active", "clever", "health"]
forEach()
?方法对数组的每个元素执行一次给定的函数。
const array = [{id:'1',name:"小李",age:'23',remark:null},{id:'2',name:"小张",age:'35',remark:null},{id:'3',name:"小王",age:'21',remark:null}];
array.forEach((item) => {
if (item.age>30){
console.log(item);
item.remark = "30+";
}
})
console.log(array)
结果如下:
> Object { id: "2", name: "小张", age: "35", remark: null }
> Array [Object { id: "1", name: "小李", age: "23", remark: null }, Object { id: "2", name: "小张", age: "35", remark: "30+" }, Object { id: "3", name: "小王", age: "21", remark: null }]
push()
:向数组的最后面插入一个或多个元素,返回结果为该数组新的长度
const arr = ["王一", "王二", "王三"];
?
const result1 = arr.push("王四"); // 末尾插入一个元素
const result2 = arr.push("王五", "王六"); // 末尾插入多个元素
?
console.log(result1); // 打印结果:4
console.log(result2); // 打印结果:6
console.log(JSON.stringify(arr)); // 打印结果:["王一","王二","王三","王四","王五","王六"]