This question already has answers here:
Why for .. in gets all the properties, but for .. of doesn't get all the values?
(2 answers)
Closed 6 years ago.
Can you explain me, please, why first console.log shows me array with both:
array.foo and item, but when I use for of loop it does not show array.foo?
let array = [3,5,8, item = 'good'];
array.foo = 'hello';
console.log(array);
for (var i of array) {
console.log( i);
}
The for-of runtime semantics tell us that we will iterate over ForIn/OfHeadEvaluation( « », AssignmentExpression, iterate). Which in turn returns us the GetIterator(exprValue) (see 8.b). GetIterator returns an iterator from the ##iterator slot (or Symbol.iterator). Which for an array returns the Array.prototype.values which uses CreateArrayIterator whose semantics are defined here.
And as you can see at %ArrayIteratorPrototype%.next( ) it iterates through the indexes from 0 through length - 1 and says nothing about other properties.
So, to summarise, the for-of does not iterate through non-index properties because the array iterator does not do so.
Related
This question already has answers here:
Access to ES6 array element index inside for-of loop
(12 answers)
Closed 2 years ago.
I understand that for of is to get the element from an array in Javascript.
for (let element of array) {
// do something with element
}
The problem is that I can't get the index inside the loop.
But I remember that at some time in the past, I have read that I can also get the index within the loop using syntax that more or less like this:
for ((index, element) of array.indexed()) {
// can access both index and element here
}
But it's hard to find it amidst of the many faces of for loop syntax alternative of Javascript. One of the answer I read is here that contains tons of indexed for loop alternative, but nothing like what I've described above.
use this
for (const [index, value] of array.entries()) {
console.log(index, value);
}
This question already has answers here:
Copy array by value
(39 answers)
Closed 2 years ago.
q = [3,2,4,1]
let copyQ = q;
copyQ.sort();
console.log(q) // 1,2,3,4 --------> This doesnt make sense.
console.log(copyQ) //1,2,3,4 -----> This makes sense
I had expected that q would remain the same, i.e unsorted as in line 1, because we had sorted copyQ, but it is not the case.
Whats going on there?
sort() function mutates initial array. As soon as your array is copied by link - it is expected. Use spread operator to avoid mutation of initial array. Spread operator will create a copy of your array that will be separate from initial one:
q = [3,2,4,1]
let copyQ = [...q];
copyQ.sort();
console.log(q)
console.log(copyQ)
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 6 years ago.
I have found that these two different methods of creating an array of arrays produce different behaviors:
// Method 1
for (var arr1 = []; arr.push([]) < len;) {}
// Method 2
var arr2 = new Array(len).fill([])
The arrays created look the same in the console, however they behave differently in my code. What could be causing this?
The difference is that in the 1st method each index points to a different array, while in the Array#fill all indexes point to the same array.
Note: the 1st method will not create an array of arrays
var len = 3;
var arr1 = [];
// Method 1
for (var arr1 = []; arr1.push([]) < len;) {} // new sub array is pushed into arr1
// Method 2
var arr2 = new Array(len).fill([]) // each place in the array is filled with a reference to the same array
arr1[0].push(1); // push to the 1st element of arr1
arr2[0].push(1); // push to the 1st element of arr2
console.log('arr1: ', JSON.stringify(arr1)); // only the 1st sub array contains 1
console.log('arr2: ', JSON.stringify(arr2)); // all sub arrays contain 1
Update: While the answer below is technically accurate, and is another difference between the two methods, #Ori Drori's answer is almost certainly what the OP is looking for.
I'll take a stab at this, but more context would be helpful.
In common practice, these two statements typically behave the same, but there is a key difference - when you use the new keyword, the Javascript interpreter calls the Array constructor.
If you were to overwrite the Array constructor, this would only apply to arr2 which was defined with the new keyword. arr1 created with the array literal would still be a Javascript array.
As an example, let's say I wrote the following code:
function Array() {
}
Method 1 would still work, but Method 2 would return a TypeError indicating that fill is not a function.
Interestingly, using the Array literal (Method 1) still calls the Array constructor, so if I did a console.log("test"); within the Array construction this would still be printed to the console when using either method. BUT, when the Array literal (Method 1) is used, the object itself still remains a standard Javascript array even if the Array constructor is overwritten.
This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
Closed 4 months ago.
If I do
var a = [].push(undefined);
console.log(a);
it gives output as 1 even though undefined was pushed to the array. Any idea why?
You're testing it the wrong way. a is not defined as the array, as I think you suppose it to be. Try this:
var a = []
a.push(undefined);
console.log(a);
You are assigning the return value of push function to variable a. push returns the length of the array after pushing the current element in context. So, it returns 1 after pushing undefined in the array.
its pushing the length of array inside not the elements
example
var a = [].push(5,6,7,8);
console.log(a); //gives 4
Push returns the new length of the array, and thats what is stored in a
There was no explicit check has been done when assigning a new property to array object. Assigning a new property in the sense, setting 0,1,2..n properties with values, based on the length of the array.
Repeat, while items is not empty
Remove the first element from items and let E be the value of the element.
Let setStatus be Set(O, ToString(len), E, true).
ReturnIfAbrupt(setStatus).
Let len be len+1.
You can see it here. Step 8.
This question already has answers here:
Elements order in a "for (… in …)" loop
(10 answers)
Sort JavaScript object by key
(37 answers)
Closed 8 years ago.
I have an object which would translate into a Dictionary in C# and I'm trying to loop through all my "keys" so that I can draw my objects in order.
Let's say that this dictionary contains three objects with the keys 1, 2 and 3.
for (var key in myDictionary) {
if (key === "indexOf" || key === "length")
continue;
// Do stuff...
}
Now, in IE9+, Chrome and Firefox, the output will be 1, 2, 3 while in IE8 the output is 2, 1, 3.
As it is crucial for my application that these objects are given in order you can understand that this is unwanted behavior.
My question, therefore, is:
Why does this happen and is there a known workaround that fixes my issue?
That happens because the properties in an object doesn't have any specific order. The order that you get the propeties is depending on the implementation, i.e. how the properties are stored internally in the object.
The browsers that return the properties in a different order than you expect aren't doing anything wrong, the actual error is to expect any specific order.
If you want the properties in a specific order, you need to sort them. You can put them in an array, sort the array, and loop through the array.