有人告诉我不要for...in在JavaScript中使用数组。为什么不?
原因是一种构造:
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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。