开发者社区> 问答> 正文

为什么在数组迭代中使用“ for…in”是个坏主意?

已解决

有人告诉我不要for...in在JavaScript中使用数组。为什么不?

展开
收起
保持可爱mmm 2020-01-08 15:40:05 395 0
1 条回答
写回答
取消 提交回答
  • 采纳回答

    原因是一种构造:

    var a = []; // Create a new empty array. a[5] = 5; // Perfectly legal JavaScript that resizes the array.

    for (var i = 0; i < a.length; i++) { // Iterate over numeric indexes from 0 to 5, as everyone expects. console.log(a[i]); }

    /* Will display: undefined undefined undefined undefined undefined 5 */

    有时可能与另一个完全不同:

    var a = []; a[5] = 5; for (var x in a) { // Shows only the explicitly set index of "5", and ignores 0-4 console.log(x); }

    /* Will display: 5 */

    还请注意,JavaScript库可能会执行以下操作,这会影响您创建的任何数组:

    // Somewhere deep in your JavaScript library... Array.prototype.foo = 1;

    // Now you have no idea what the below code will do. var a = [1, 2, 3, 4, 5]; for (var x in a){ // Now foo is a part of EVERY array and // will show up here as a value of 'x'. console.log(x); }

    /* Will display: 0 1 2 3 4 foo */

    问题来源于stack overflow

    2020-01-08 15:40:20
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载