数组常用遍历方法
这里是knockkey,这是我坚持写博客的第三天
1. 原生for循环
- for循环,
性能最强 - 可以
continue或break - 同时需要用到
item和index,并且还需要根据条件continue或者break的场景
const list = [1, 2, 3];
const listNew = []
for (let i = 0, length = list.length; i < length; i++) {
if (i == 1) {
continue;
}
listNew[i] = list[i]
}
console.table(listNew); // [1, undefined, 3]
2. for...in...
- 可以
continue和break
const arr = ['a', 'b', 'c']
const arrNew = []
for (let index in arr) {
if (index == 1) {
continue;
}
arrNew[index] = arr[index]
}
console.table(arrNew); //['a',undefined , 'c']
3. for...of...
es6新增的方法- 可以
continue和break
const list = [1, 2, 3];
const listNew = []
for (let item of list) {
if (item == 2) {
continue;
}
listNew.push(item)
}
console.log(listNew); //[1,3]
4. forEach
Array.prototype上内置的, 即每个数组实例都能调用的方法- 不支持
continue和break
const list = [1, 2, 3]
const listNew = []
list.forEach(item => {
listNew.push(item)
});
console.log(listNew); //[1,2,3]
forEach的其他写法
const arr = ['a', 'b', 'c']
const arrNew = []
Array.prototype.forEach.call(arr, function (item) {
arrNew.push(item)
});
console.log(arrNew); // ['a', 'b', 'c']