Loop Over Array in Javascript [duplicate] - javascript

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 )

Related

What is the simple way to get value and index on For of loop out of an array in Javascript / ReactNative? [duplicate]

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

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.

JavaScript: store function method to variable [duplicate]

This question already has answers here:
JavaScript Function Context Incorrect
(3 answers)
Closed 7 years ago.
I have a variable a that can be either an object or an array of objects. I have an array array.
I want to append a to array, so I thought of using either Array.prototype.push.call or Array.prototype.push.apply with a ternary operator as follows:
var a = "hello"; // or var a = ["hello", "world"];
var array = [];
var append = ($.isArray(a)) ? Array.prototype.push.apply : Array.prototype.push.call;
append(array, a); // Uncaught TypeError: undefined is not a function
($ being jQuery)
I'm new to JavaScript and I guess there is a good reason why this doesn't work but I couldn't find it. Can't apply or call be assigned to a variable? (They are not real functions?) Or is something missing on the call to append()?
Note: I know I could do this with if/else but I'd rather like to understand why I can't assign these methods to a variable and call it.
Minor additional question: I want to do this because I get a from a JSON API and if I understand correctly, JSON can't contain arrays of one single object. Although I feel that what I'm trying to do must be very common, I also couldn't find how other developers deal with this. Is there a better way than testing whether a is an array or not and use apply() or not accordingly?
This happens because call and apply are instance methods. They are critical to the context object this.
Eventually you should execute append.call(Array.prototype.push, array, a) because call or apply need function push to be passed as this
You don't need any if, just use concat
var array = [];
var a = "hello"; // or var a = ["hello", "world"]
array = array.concat(a);

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.

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

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.

Categories

Resources