遍历数组的方法
1、常见的for循环:
var arr = [1,2,3,4];
for(var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
2、forEach和map:
var arr = ['a', 'b', 'c', 'd'];
arr.forEach((e, i) => console.log(i, e) );
//0 'a'
//1 'b'
//2 'c'
//3 'd'
var arr = ['a', 'b', 'c', 'd'];
arr.map((e, i) => console.log(i, e) );
//0 'a'
//1 'b'
//2 'c'
//3 'd'
3、for...of
var arr = [1, 2, 3]
for(let key of arr){
console.log(key);
}
遍历对象
1、for ... in
var xiaohua = {age: 18, height: 185, country: "China"}
for( let key in xiaohua){
console.log(key, xiaohua[key]);
}
//age 18
//height 185
//country "China"
过滤数组
filter
var arr = [
{key: "1", name: "小王", age: 22, address: "西湖区湖底公园1号"},
{key: "2", name: "小张", age: 32, address: "西湖区湖底公园2号"},
{key: "3", name: "小李", age: 42, address: "西湖区湖底公园3号"}
];
var ageArr = [22, 32];
// 过滤arr数组中age符合ageArr数组元素的值,即类似于删除arr表格中的第第一项和第二项
var newArr = arr.filter(item => {
if(ageArr.indexOf(item.age) > -1){
return;
} else {
return item;
}
});
// 此时newArr为 [{key: "3", name: "小李", age: 42, address: "西湖区湖底公园3号"}]