有用到object对象的转换成数组,而后又想到了遍历方法,因此,也想记录下
for (let i = 0; i < 5; i++) { if (i == 3) break; console.log("The number is " + i); /* 只输出 0 , 1 , 2 , 到3就跳出循环了 */ } for (let i = 0; i <= 5; i++) { if (i == 3) continue; console.log("The number is " + i); /* 不输出3,由于continue跳过了,直接进入下一次循环 */ }
const temporaryArray = [6,2,3,4,5,1,1,2,3,4,5]; const objectArray = [ { id: 1, name: 'd' }, { id: 2, name: 'd' }, { id: 3, name: 'c' }, { id: 1, name: 'a' } ]; const temporaryObject = { a: 1, b: 2, c: 3, d: 4, }; const length = temporaryArray.length;
for(let i = 0; i < length; i++) { console.log(temporaryArray[i]); }
/* for in 循环主要用于遍历普通对象, * 当用它来遍历数组时候,也能达到一样的效果, * 可是这是有风险的,由于 i 输出为字符串形式,而不是数组须要的数字下标, * 这意味着在某些状况下,会发生字符串运算,致使数据错误 * */ for(let i in temporaryObject) { /* hasOwnProperty只加载自身属性 */ if(temporaryObject.hasOwnProperty(i)) { console.log(temporaryObject[i]); } }
for(let i of temporaryArray) { console.log(i); }
let a = temporaryArray.forEach(function(item, index) { console.log(index, item); });
temporaryArray.map(function(item) { console.log(item); });
temporaryArray.filter(function(item) { console.log(item%2 == 0); });
let newArray = temporaryArray.some(function(item) { return item > 1; }); console.log(newArray);
let newArray1 = temporaryArray.every(function(item) { return item > 6; }); console.log(newArray1);
accumulator:初始值或者累加计算结束后的返回值, currentValue遍历时的当前元素值,currentIndex当前索引值,array当前数组
initValue为初始值,若不添加参数initValue,则accumulator为当前数组的第一个元素值,若添加,则accumulator为initValue值,累加器accumulator从initValue开始运算
let temporaryObject3 = {}; let newArray2 = objectArray.reduce(function(countArray, currentValue) { /* 利用temporaryObject3里存放id来判断原数组里的对象是否相同,若id相同,则继续下一步,不一样则将该对象放入新数组中 * 则countArray为去重后的数组 * */ temporaryObject3[currentValue.id] ? '' : temporaryObject3[currentValue.id] = true && countArray.push(currentValue); return countArray; }, []); console.log(newArray2);
正在努力学习中,若对你的学习有帮助,留下你的印记呗(点个赞咯^_^)
往期好文推荐:css