Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - 为什么在数组迭代中使用“ for…in”是个坏主意?(Why is using “for…in” with array iteration a bad idea?)

I've been told not to use for...in with arrays in JavaScript.(有人告诉我不要将for...in用于JavaScript for...in的数组。)

Why not?(为什么不?)   ask by lYriCAlsSH translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason is that one construct:(原因是一种构造:)

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 */ can sometimes be totally different from the other:(有时可能与另一个完全不同:) 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 */ Also consider that JavaScript libraries might do things like this, which will affect any array you create:(还请注意, 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 */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...