Home > Article > Web Front-end > Introduction to javascript traversal method (code example)
This article brings you an introduction to the JavaScript traversal method (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
It is useful to convert the object object into an array, and then I thought of the traversal method, so I also want to record it
1. Terminate or jump out of the loop
break jumps out of the loop body, the loop body is over
return Terminate function execution
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跳过了,直接进入下一次循环 */ }2. Traversal method
Fake data
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);
total: initial value or The return value after the calculation is completed, the current element value when currentValue is traversed, the current index value of currentIndex, and the current array of array
If no parameter is specified - empty array [], the cumulative variable total defaults to the value of the first elementlet 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);
The above is the detailed content of Introduction to javascript traversal method (code example). For more information, please follow other related articles on the PHP Chinese website!