End

JavaScript 循环 迭代 遍历

本文地址

JavaScript 循环 迭代 遍历

let array = [1, "string", false];

for

for (let i = 0; i < array.length; i++) {
    console.log(array[i])
}

while

let i = 0
while (i < array.length) {
    console.log(array[i])
    i++;
}

for in

for (let i in array) {
    console.log(array[i]);
}

forEach

array.forEach((val, index, array) => {
    // 当前值,当前 index,当前 Array
    console.log(`${val} ${index} ${array[index]} `);
});

for of

在 ES6 中引入的 for...of 循环,以替代 for...in 和 forEach() ,并支持新的迭代协议。

for...of 允许遍历 Arrays(数组), Strings(字符串), Maps(映射), Sets(集合)等可迭代的数据结构等。

for (let entry of array) {
    console.log(entry);
}

every 和 some

forEach 在 iteration 中是无法返回的,想要返回时可以使用 every 和 some。

array.every((val, index, array) => {
    // 当前值,当前 index,当前 Array
    console.log(`${val} ${index} ${array[index]} `);
    // Return false will quit the iteration
    return true;
});

array.some((val, index, array) => {
    // 当前值,当前 index,当前 Array
    console.log(`${val} ${index} ${array[index]} `);
    // Return true will quit the iteration
    return false;
});

for in 循环的局限

for...in 主要用于遍历对象的可枚举属性,而不是数组的元素。

用 for...in 遍历数组可能有以下几个问题:

  • 不可靠的内容:for...in 遍历的是 string 类型的索引,而非数组元素
  • 不可靠的顺序:for...in 不保证按照索引顺序遍历数组
  • 有潜在的问题:如果数组或其原型链上有自定义属性,for...in 也会遍历到这些非数组元素的属性
var array = [3, 4, 5]
array.city = "bqt"
for (x in array) {
    console.log(x + 1) // 打印的是 01,11,21,city1
}

2016-12-13

posted @   白乾涛  阅读(1538)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示