JS array traversal must be used in the project. In order to write elegant code, use the method in the right place. Here we will compare several methods and display them in es6. , you need to build a conversion es5 environment. This is not the focus of this article. You can write about this in the next article.
is the most frequently used and is used by the front-end, indicating that I will only use the for loop at the beginning. . .
let arr = ['123', '456', '789'];for (let i = 0; i < arr.length; i ++) { console.log(arr[i]); }
The most commonly used, but there is room for optimization:
for (let i = 0, len = arr.length; i < len; i ++) { console.log(arr[i]); }
Use temporary variables to store the length value to avoid repeatedly obtaining the array length.
The new loop method in es6 is simpler and more efficient than the for loop in es5. It also provides three new methods:
key() is a traversal of key names;
value() is a traversal of key values;
let arr = ['科大讯飞', '政法BG', '前端开发']; for (let item of arr) { console.log(item); } // 输出数组索引 for (let item of arr.keys()) { console.log(item); } // 输出内容和索引 for (let [item, val] of arr.entries()) { console.log(item + ':' + val); }
let arr = ['科大讯飞', , '政法BG', , '前端开发']; arr.forEach((val,index)=>console.log(index,val));
let arr = [{ label: '科大讯飞', value: 1 }, { label: '政法BG', value: 2 }, { label: '前端开发', value: 3 }]; const arr1 = arr.filter(list => list.value === 1); console.log(arr1);
if (arr.some(list => list.value === 1)) { console.log('执行了!') }
let arr = [1, 2, 3, 4]; onst arr1 = arr.map(list => list * 2); console.log(arr1);
Related recommendations:
Common methods for traversing arrays
3 ways to traverse list collections
The above is the detailed content of Summary of JS array traversal methods. For more information, please follow other related articles on the PHP Chinese website!