Difference between for vs for var in javascript
我在PHP中填充一个关联数组,并在JS函数中访问该数组。我使用json_encode()将php数组转换为js数组。我使用IE8来运行这个应用程序。在某些机器中,IE8用于(;;)工作,但在其他机器中失败。在有些机器中,IE8用于(var-in)工作,但在其他机器中失败。以下代码有什么区别?
1 2 3 | for (var k = 0; k < ruleList.length; k++){ //do something } for (var x in ruleList){ //do something } |
好吧,
1 2 3 4 5 | var x = [1, 2, 3]; for(var i in x) console.log(x[i]); var o = {1:1, 2:2, 3:3}; for(var i in o) console.log(o[i]); |
而
1 2 3 4 5 | var x = [1, 2, 3]; for(var i=0; i<x.length; i++) console.log(x[i]); var o = {1:1, 2:2, 3:3}; for(var i=0; i<o.length; i++) console.log(x[i]); // returns undefined because object o doesn't have property length |
但可以使用
1 2 3 | var o = {1:1, 2:2, 3:3}; var keys = Object.keys(o); for(var i=0; i<keys.length; i++) console.log(o[keys[i]]); |
通常的做法是将
javascript没有关联数组(严重)。因此,根据您的PHP数据,您可能以完全不同的类型结束,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php $consecutive_keys = array( 0 => 'Zero', 1 => 'One', 2 => 'Two', ); $sparse_keys = array( 5 => 'Five', 10 => 'Then', ); $dictionary = array( 'Foo' => 'Bar', ); echo json_encode($consecutive_keys) . PHP_EOL; echo json_encode($sparse_keys) . PHP_EOL; echo json_encode($dictionary) . PHP_EOL; |
1 2 3 | ["Zero","One","Two"] <-- Array {"5":"Five","10":"Then"} <-- Object {"Foo":"Bar"} <-- Object |
因为javascript数组是javascript对象的一个子集,所以在这两种情况下,您都会发现
这个问题已经有了讨论和答案。
提出问题以了解区别。
The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement or a set of statements executed in the loop.
正如MDN文档中所说:
The for...in statement iterates over the enumerable properties of an
object, in arbitrary order. For each distinct property, statements can
be executed.
第一条语句用于数组,而第二条语句用于获取对象的所有键。