js中的 for, for in, for of foreach,filter使用
下面是对数组进行循环
var array = [
{ id: 1, name: 'ohzri', birth: '1999.09.09', city: '湖北', salary: 9379 }, { id: 2, name: 'rqgfd', birth: '1999.10.28', city: '湖北', salary: 1060 }, { id: 3, name: 'fwfsh', birth: '1999.09.17', city: '广西', salary: 9736 }, { id: 4, name: 'bqibt', birth: '1999.04.20', city: '湖南', salary: 9471 }, { id: 5, name: 'ypklq', birth: '1999.06.28', city: '山东', salary: 3123 }, { id: 6, name: 'lupnr', birth: '2001.10.03', city: '河南', salary: 4630 }
];
使用:for
var arr1 = [];
for (var i = 0; i < array.length; i++) { if (array[i].salary >= 3000 && array[i].salary <= 3500) { arr1.push(a[i]); } }
使用:for in 注意,for in 使用于循环对象,不建议对数组使用,因为输出的不是值,而是下标
var arr2 = [];
for (let var1 in a) { if (var1.salary >= 3000 && var1.salary <= 3500) { arr2 = var1; } }
使用:for of
var arr3 = [];
for (let var2 of a) {
if (var2.salary >= 3000 && var2.salary <= 3500) { arr3.push(var2); } }
使用:Foreach
var arr4 = [];
a.forEach(function(i) { if (i.salary >= 3000 && i.salary >= 3500) { arr4.push(i); } });
使用:filter
以下两句代码是等效:
var arrayfilter = a.filter(function(v){ return v.salary >= 3000 && v.salary >= 3500 });
var arrayFilter = a.filter((v) => v.salary >= 3000 && v.salary <= 3500);
可以输出看效果:
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
console.log(arrayFilter);