12

I populate an associative array in PHP and access the array in a JS function. I use json_encode() to convert PHP array to JS array. I use IE 8 to run this application. In some machines with IE 8 for(;;) works but fail in others. In some machines with IE 8 for(var in) works but fail in others. What's the difference between the following code?

for (var k = 0; k < ruleList.length; k++){ //do something } 

for (var x in ruleList){ //do something }
Dheeraj Kumar
  • 410
  • 6
  • 16
KeepCalmAndCode
  • 207
  • 2
  • 12

4 Answers4

4

Well, for(i in x) works with both, arrays and objects

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]);

While for(;;) works only with arrays

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

But you could use Object.keys to get array of keys of object

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]]);

Common practice is to use for(i in x) for objects and for(;;) for arrays

Buksy
  • 11,571
  • 9
  • 62
  • 69
2

Like it says in the MDN documentation:

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

Your first statement is used for an array, while the second is used to get all keys of an object.

gleerman
  • 1,793
  • 4
  • 24
  • 38
0

Already there are discussions and answers of this question.

Refer Question to know the difference.

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.

Community
  • 1
  • 1
Shrabanee
  • 2,706
  • 1
  • 18
  • 30
0

JavaScript does not have associative arrays (seriously). So depending on your PHP data you might end with entirely different types, e.g.:

<?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;
["Zero","One","Two"]     <-- Array
{"5":"Five","10":"Then"} <-- Object
{"Foo":"Bar"}            <-- Object

Since JavaScript arrays are a subset of JavaScript objects you'll find that var x in ruleList (which loops through object properties) kind of works in both cases, but it won't do what you expect when you have an array.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360