var arr = [1,2,3];
array.prototype.test=function(){} arr.name='jq'
/* * index是number类型的,可以使用break,continue,return语句 * 可以遍历对象 */
for (var index = 0, length = arr.length; index < length; index++) { console.log(index); // 0, 1, 2 console.log(arr[index]); // 1, 2, 3 }
/* * 除了遍历数组元素外,还会遍历自身可枚举属性,以及原型链上属性 * 适用于普通对象,不适合数组遍历 * 可以使用break,continue,return语句 */ for (var index in arr) { console.log(index); // 0, 1, 2, name, test console.log(arr[index]); // 1, 2, 3, jq, ƒ (){} }
/* * 只遍历数组元素 * 只适用于数组,set,map,类似数组对象,不适合普通对象对象 * 可以使用break,continue,return语句 */ for (var item of arr) { console.log(item); // 1, 2, 3 }
/* * 只遍历数组元素 * 参数:item 数组元素当前值,index 数组索引,array 数组本身 * 只适用于数组,set,map,类似数组对象,不适合普通对象对象 * break,continue,return语句无效 */ arr.foreach(function(item, index, array) { console.log(index); // 0, 1, 2 console.log(item); // 1, 2, 3 })
/* * 只适用于数组,set,map,类似数组对象,不适合普通对象对象 * break,continue,return语句无效 * 参数:item 数组元素当前值,index 数组索引,array 数组本身 */ arr.map(function(item, index, array) { console.log(index); // 0, 1, 2 console.log(item); // 1, 2, 3 return 0; })
/* * reduce 使用回调函数迭代地将数组简化为单一值 * 只适用于数组,set,map,类似数组对象,不适合普通对象对象 * 参数:callback 和 初始值 * accumulator: 函数上一次调用的返回值 * item: item 数组元素当前值 */ (1) 省略初始值,则accumulator为 arr[0], item为arr[1], index为1 arr.reduce(function(accumulator, item, index, array) { return accumulator + item; //求数组元素和 }); 执行顺序: 1 + 2 3 + 3 (2) 有初始值,则accumulator为initvalue,item为arr[0], index为0 arr.reduce(function(accumulator, item, index, array) { return accumulator + item; //求数组元素和 }, 0); 执行顺序: 0 + 1 1 + 2 3 + 3 优点:减少数组迭代次数
/* * 只适用于数组,set,map,类似数组对象,不适合普通对象对象 * item: item 当前数组元素 */ arr.filter(function(item, index, array) { return (item > 1); }) 结果:[2, 3]
* 只适用于数组,set,map,类似数组对象,不适合普通对象对象 * item: item 当前数组元素 */ arr.find(function(item, index, array) { return (item > 1); })
结果:2
如对本文有疑问, 点击进行留言回复!!
egg项目npm/cnpm出错Connect timeout
网友评论