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 }
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.
Difference for..in and for..of : The only difference between them is the entities they iterate over: for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.
forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm. Unlike in AssemblyScript, micro-optimizations of the for loop don't make sense for arrays in JavaScript.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With