最普通的循环 效率最高 兼容ie6
tips:for循环更适用于循环的开始和结束已知,循环次数固定的场合;while循环更适合于条件不确定的场合
兼容ie6,效率最差(效率可看最下面的对比) for in 会把继承链的对象属性都会遍历一遍,所以会更花时间.
var arr = ['red', 'green', 'blue'];
var obj = {
name:'张三',
age:20
}
for(k in obj){
console.log(k); //name , age
console.log(obj[k]); // 张三 , 20
}
for(k in arr){
console.log(k); // 0 , 1 ,2
console.log(arr[k]); // red, green ,blue
}
ie不兼容 【for-of 语句只遍历可迭代对象的数据。】原生具备 Iterator 接口的数据结构如下。ArrayMapSetStringTypedArray函数的 arguments 对象NodeList 对象更多迭代器 阅读:http://es6.ruanyifeng.com/#docs/iterator
var arr = ['red', 'green', 'blue'];
for(var v of arr) {
console.log(v); // red green blue
}
区别:for of 和 for in的区别for-in 语句以原始插入顺序迭代对象的可枚举属性。for-in会把继承链的对象属性都会遍历一遍,所以会更花时间.
every 、 filter、forEach、map、reduce、some 都是兼容ie9
map,filter 是返回新的数组 (形象区分几个循环方法的区别参考:https://www.zhihu.com/question/24927450)
方法说明:测试数组的所有元素是否都通过了指定函数的测试。 遇到有不满足的会提前终止整个循环
场景:检测每一项的selected字段都是被选中为true
案例:
var arr = [
{id:1,name:"zhangsan1",selected:false},
{id:2,name:"zhangsan2",selected:false},
{id:3,name:"zhangsan3",selected:true},
];
var reslut = arr.every(function(el,index,arr){
console.log(el);
return el.selected==true;
});
console.log(reslut); //false
var arr = [
10,20,30
];
var arr1 = arr.filter(function(el,index,arr){
return el > 10;
});
console.log(arr1); // 20 30
var arr = [
{id:1,name:"zhangsan1",selected:false},
{id:2,name:"zhangsan2",selected:false},
{id:3,name:"zhangsan3",selected:true},
];
arr.forEach(function(el,index,arr){
console.log(el)
});
var arr = [
{id:1,name:"zhangsan1"},
];
var arr1 = arr.map(function(el,index,arr){
var newObj = {};
newObj.id = el.id;
newObj.selected = false;
return newObj;
});
console.log(arr); // [{id:1,name:"zhangsan1"}]
console.log(arr1); // [{id:1,selected:false}]
案例2: es6写法
var numbers = [1, 5, 10, 15];
var doubles = numbers.map( x => x ** 2); //[2,10,20,30]
案例3:重格式化数组 //不改变原数组
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(function(obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
// reformattedArray 数组为: [{1: 10}, {2: 20}, {3: 30}],
var total = [0, 1, 2, 3].reduce(function(sum, value) {
return sum + value;
}, 0);
// total is 6
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]
const isBiggerThan10 = (element, index, array) => {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10);
// false
[12, 5, 8, 1, 4].some(isBiggerThan10);
// true
案例2: 是否包含id为1 对象
var arr = [
{id:1,name:"zhangsan1"},
{id:2,name:"zhangsan2"},
];
var flag = arr.some(function(element, index, array){
console.log(element.id)
return element.id == 1;
});
console.log(flag)
http://www.jb51.net/article/60502.htm
https://juejin.im/post/5a3a59e7518825698e72376b#heading-4