For loop in array reads 'remove'? [duplicate] - javascript

This question already has answers here:
Problems with JavaScript "for in" loop
(3 answers)
Closed 9 years ago.
I just experienced the strangest thing, this is the code I'm actually using :
for (iter in data.List) {
console.log(iter);
}
As you would expect, the log should give the number of each row (0, 1, 2...), instead it gives me this :
0
1
2
remove
Knowing that my array only has 3 rows
Did anybody ever encountred this ?

Basically, the problem is that you are iterating through your array using a for in loop, which is not meant for iteratung through arrays. Its intent is to iterate through all properties of an object, and apparently there is a property called remove on your array.
For more details on why for in is a bad idea when it comes to arrays, see Why is using "for...in" with array iteration a bad idea?.
As solution, I'd suggest to use an indexed for loop. This type of loop does not care about properties, hence you are fine. So it basically comes down to a very classical:
for (var i = 0; i < data.List; i++) {
console.log(data.List[i]);
}
By the way: You should not uppercase anything in JavaScript, unless it's a constructor function. Hence it should be data.list.
PS: A nice read when it comes to arrays and (mis-)using them, read Fun with JavaScript Arrays, a quite good read.

Yes, that is how for..in works in JavaScript. It enumerates over all object properties (not Array indexes). Simple solution: don't use for..in on Arrays, because that's not what it is for.

Related

Why can we use the .length property in string types? [duplicate]

This question already has answers here:
How does primitive types in Javascript have methods and Properties? [duplicate]
(2 answers)
Closed last year.
Hello I'm new to JS and object-oriented programming in general.
I have two questions considering this
let arr = [1,2,3]
let a = 'hi'
When I run typeof(), arr is 'object' and a is 'string' right?
So my question is ,
When using arr.length to get the length of the array, what's the principle behind it? To be specific, I don't understand how I could get the length property though I've never initialized it. Does JS automatically set a length property value when we generate an object? How does it work?
Doesn't property only exist in objects? But why can we get the length of variable a using a.length? I thought objectname.property thing was for objects.
When you declare [1,2,...] you are declaring an object of class Array, which, in it's prototype, has a "length" property. Think of it as a variable that gets updated when you add or remove elements from the array.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/length
Strings are also objects in Javascript, and a string is also considered an array of characters, thus having the "length" property as well.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

Can a member function be added to the Array class in JavaScript without showing up in a for-in loop? [duplicate]

This question already has answers here:
adding custom functions into Array.prototype
(7 answers)
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 2 years ago.
In some code I'm working on I created a JavaScript function that is applied solely to Arrays, and I thought I'd try adding it as a member function.
I added it like so:
Array.prototype.myfunc = function(a){
...
}
Which works fine for the most part. The problem I run into then is with a for-in loop. It includes that function in the loop. If I then type in this snippet:
var bar, foo = ['alpha', 'bravo', 'charlie'];
for(bar in foo) console.log(foo[bar]);
Then the output is along the lines of:
alpha
bravo
charlie
function myFunc(a){
...
}
So is there any way of doing this but avoiding it showing in the for-in loop?
You can use Object.defineProperty to create non-enumerable attributes of any object, including arrays. Remember in JavaScript, arrays are just objects with numbers for keys, which is why attributes you add to them come up in a forEach.

Loop Over Array in Javascript [duplicate]

This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 8 years ago.
I'm using Google Chrome's Console window to try and figure out why I'm not able to loop over an array in javascript.
I have a javascript object called moveResult that looks like this:
I'm trying to loop over the MoveParts in javascript like this:
for (var movePart in moveResult.MoveParts) {
console.log(movePart.From);
};
I always get undefined instead of the actual value. However, If I try to access the first item explicitly I get what I want, like this:
console.log(moveResult.MoveParts[0].From);
The result of this is "b1".
Why isn't my loop working?
I've also tried a foreach:
moveResult.MoveParts.foreach(function (movePart) {
console.log(movePart.From);
};
I'm trying to loop over the MoveParts in javascript like this:
for (var movePart in moveResult.MoveParts) {
console.log(movePart.From);
};
I always get undefined instead of the actual value.
Don't use for-in to loop through arrays, that's not what it's for. for-in is for looping through object properties. This answer shows various ways to loop through arrays.
The reason your for-in didn't work is that movePart is the key, not the actual entry, so if you were using an object (not an array!) you would have used moveResult.MoveParts[movePart].From.
Your forEach version only failed because:
It's forEach, not foreach. Capitalization matters in JavaScript.
You were missing the closing ) on the function call.
The answer linked above has full examples of forEach and others, but here's how yours should have looked:
moveResult.MoveParts.forEach(function (movePart) {
// Capital E -----------^
console.log(movePart.From);
});
// ^---- closing )

JavaScript for..in statement give unexpected results in IE8 [duplicate]

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.

Putting items in JavaScript arrays on arbitrary indices [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are Javascript arrays sparse?
Is the following "safe" in JavaScript? (as in, can be expected to work reliably on all JavaScript engines)
a = [];
a[100] = "hello";
a[100] == "hello"; // should be true
Yes. Arrays in JavaScript are sparse and your code is expected to work in all JavaScript implementations.
You can get into requirements in the section 15.4 of the specification(PDF).
Short summary: array is special object that have length property adjusted when one adds elements at properties with numeric names (like `a[123]="test"). Other methods like join take length into account duuring operations.
Yes, why wouldn't it work? Its perfectly acceptable syntax.
You can even assume
a[100] === "hello"; // will return true

Categories

Resources