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:undefinedundefinedundefinedundefinedundefined5*/
有时可能与另一个完全不同:
var a = [];a[5] = 5;for (var x in a) {// Shows only the explicitly set index of "5", and ignores 0-4console.log(x);}
/* Will display:5*/
// 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:01234foo*/
for ... in ...的问题-只有当程序员并不真正理解该语言时才会成为问题;它不是真正的bug或任何东西-是它迭代对象的所有成员(好吧,所有enumerable成员,但这是现在的细节)。当你想迭代只是数组的索引属性时,保持语义一致的唯一保证方法是使用整数索引(即for (var i = 0; i < array.length; ++i)样式循环)。
//Non-associativevar arr = ['a', 'b', 'c'];for (var i in arr)alert(arr[i]);
//Associativevar arr = {item1 : 'a',item2 : 'b',item3 : 'c'};
for (var i in arr)alert(arr[i]);
// C#char[] a = new char[] {'A', 'B', 'C'};foreach (char x in a) System.Console.Write(x); //Output: "ABC"
// Javachar[] a = {'A', 'B', 'C'};for (char x : a) System.out.print(x); //Output: "ABC"
// PHP$a = array('A', 'B', 'C');foreach ($a as $x) echo $x; //Output: "ABC"
// JavaScriptvar a = ['A', 'B', 'C'];for (var x in a) document.write(x); //Output: "012"
function Stack(...a){var stack = new Array(...a);Object.setPrototypeOf(stack, Stack.prototype);return stack;}Stack.prototype = Object.create(Array.prototype); // now stack has full access to array methods.Object.defineProperty(Stack.prototype,"constructor",{value:Stack}); // now Stack is a proper constructorObject.defineProperty(Stack.prototype,"peak",{value: function(){ // add Stack "only" methods to the Stack.prototype.return this[this.length-1];}});var s = new Stack(1,2,3,4,1);console.log(s.peak());s[s.length] = 7;console.log("length:",s.length);s.push(42);console.log(JSON.stringify(s));console.log("length:",s.length);
for(var i in s) console.log(s[i]);
var a = [];a[0] = "zero";a[10000000] = "ten million";console.time("for loop on array a:");for(var i=0; i < a.length; i++) a[i] && console.log(a[i]);console.timeEnd("for loop on array a:");console.time("for in loop on array a:");for(var i in a) a[i] && console.log(a[i]);console.timeEnd("for in loop on array a:");
const arr = [];arr[3] = 'foo'; // resize the array to 4arr[4] = undefined; // add another element with value undefined to it
// iterate over the array, a for loop does show the undefined elementsfor (let i = 0; i < arr.length; i++) {console.log(arr[i]);}
console.log('\n');
// for in does ignore the undefined elementsfor (let el in arr) {console.log(arr[el]);}