In the following code sample i get a strange behavior
var data = ['xxx', 'yyy'];
for (var i in data)
{
var a = i;
var b = data[i];
}
The two first iterations works just fine. I get index "0" and "1" in i, but then it loops one extra time and now the i is "sum". Is this by design or what is this extra iteration used for? The result in my case is always empty and it messes up my code. Is there a way to not do his extra loop?
BR
Andreas
It looks like you (or some other code you've included) have added extra properties onto the Array prototype. What you should be doing is checking to see whether the object you're iterating over actually has that property on itself, not on its prototype:
for (i in data) {
if (data.hasOwnProperty(i)) {
a = i;
b = data[i];
}
}
That said, you should never use for .. in on arrays. Use a regular for loop.
See here for more information: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
You are looping through an Array, not through an Object. For arrays it's better to use:
for (var i=0; i<data.length; i=i+1){
/* ... */
}
In your loop every property of the Array object is taken into account. That makes the for ... in loop for array less predictable. In your case it looks like sum is a property (method) that's added to Array.prototype elsewhere in your code.
There are more ways to loop through arrays. See for example this SO-question, or this one
Just for fun, a more esoteric way to loop an array:
Array.prototype.loop = function(fn){
var t = this;
return (function loop(fn,i){
return i ? loop(fn,i-1).concat(fn(t[i-1])) : [];
}(fn,t.length));
}
//e.g.
//add 1 to every value
var a = [1,2,3,4,5].loop(function(val){return val+1;});
alert(a); //=> [2,3,4,5,6]
//show every value in console
var b = [1,2,3,4,5].loop(function(val){return console.log(val), val;});
Here's a way to safely iterate.
var data = ['xxx', 'yyy'];
for (var i = 0; i < data.length; i++)
{
var a = i;
var b = data[i];
}
What you are getting is an method coming from extending the Array object, I guess you are using some library where is something like
Array.prototype.sum = function () {...};
Perhaps setting data like this would work better: var data = {0:'xxx', 1:'yyy'};
First of all data is an object. Try to add console.log(a); and console.log(b); inside your loop and you'll see.
Related
I have an assignment which i need to sole but i am really stuck and can't make a progress. The assignment consist in an array of elements like this
const appleHolderLine = ['Rome', 'Ambrosia', 'Rome', 'RedDelicious', 'Akane','RedDelicious', 'SweeTango', 'RedDelicious', 'RedDelicious', 'Opal', 'Winesap', 'RedDelicious', 'Empire', 'RedDelicious', 'Liberty'];
Firstly it is needed to declare a variable lineCount which count for every element of the array and a reference to an object called appleMap.
Than the challenge consist in looping through the array and the elements of the array would be the object keys with no duplicates and the values would be an array of idexes of the specific element place of the array. To give an example how it should look like:
Example:
const appleHolderLine = ['GreenApples', 'RedDelicious','OrangeApples', 'PurpleApples', 'RedDelicious']
console.log (lineCount, appleMap)
Should Log:
5, {'GreenApples':[0], 'RedDelicious': [1,4], 'OrangeApples':[2], 'PurpleApples': [3]}
My progress so far
var lineCount = 0;
var appleMap = {};
for (let i = 0; i < appleHolderLine.length; i++){
lineCount++;
// if element in the array exist in the array
appleMap[appleHolderLine[i]] = [i];
}
Could you give me a hint of how to solve this, i am really stuck.
Basically you can create an empty array the first time and keep pushing like below
var lineCount = 0;
var appleMap = {};
for (let i = 0; i < appleHolderLine.length; i++){
lineCount++;
if(!appleMap[appleHolderLine[i]])
appleMap[appleHolderLine[i]] = []
appleMap[appleHolderLine[i]].push(i);
}
You could use Array.prototype.reduce which is a more advanced construct javascript provides. Please refer to answer by CodeManiac below for the same.
The above answer is to clarify the basic idea and hint on how you could think
Also, lineCount can be obtained by using appleHolderLine.length directly.
You don't need an extra variable ( Line count ) here, simply loop over the value use, use the index to access value, check if there's nothing present for that key then just initialize it with empty array, push index to the key in each iteration
const appleHolderLine = ['GreenApples', 'RedDelicious','OrangeApples', 'PurpleApples', 'RedDelicious']
var appleMap = {};
for (let i = 0; i < appleHolderLine.length; i++){
if(!appleMap[appleHolderLine[i]]){
appleMap[appleHolderLine[i]] = []
}
appleMap[appleHolderLine[i]].push(i);
}
console.log(appleMap)
You can simply use reduce
const appleHolderLine = ['GreenApples', 'RedDelicious','OrangeApples', 'PurpleApples', 'RedDelicious']
let final = appleHolderLine.reduce((op,inp,i)=>{
op[inp] = op[inp] || []
op[inp].push(i)
return op
},{})
console.log(final)
Line count is simply same as length of array, let lineCount = appleHolderLine.length
I suppose, the shortest answer is the functional one.
const appleHolderLine = ['GreenApples', 'RedDelicious','OrangeApples', 'PurpleApples', 'RedDelicious']
result = appleHolderLine.reduce((a,c,i) => { if(a[c]) a[c].push(i); else a[c]=[i]; return a; }, {})
console.log(result)
But I am not sure that you are expected to deliver a functional solution. Still, you might find it useful. The idea is that the reduce method starts with an empty object and iterates through the array. In each iteration, it checks if the current element c is already a field of the accumulator a. If so adds its index i to the specific field, if not, initializes the field with the current element as name and the index as a single-element array as value.
How to get every variable of loop into an array and call all the variables in some other variable.
I am very new to array. I don't have any idea how to solve this.
Suppose I have an Array[]
and the variable in an array is i, so i1, i2, i3 ....... in
n is the number of times loop will run.
So
for (i=1; i<=n, i++) {
//I need an array called here.
//there will be some code play here
//There will be some value returned after the code it could be text or no.
}
then I want to assign all the values of array into a variable with comma separated
var k = array{} i.e k = "i1,i2,i3,......in"
I try to find on Google but not able to find any solution.
This example is a reference for what I want to achieve actually.
You will declare the array before you enter the for loop. You will then perform your logic and .push() the new values into the array inside of the for loop. After the for loop, you would then want to .join() the array. This will assign the values of your array as a string to your new variable.
var yourArray = [];
for(i = 1; i <= n; i++) {
// some logic...
yourArray.push(newValue);
}
var yourNewVariable = yourArray.join(", ");
While this should be very easy to Google, here's how you do it:
for (var i = 1; i <= k.length; i++) {
var item = k[i];
// ...do something with item
}
When you become more versed in JS, look into using .forEach or .map:
k.forEach(function(item) {
// ...do something with item
});
Suppose I have a global object that looks like this:
var TheFruits = {
323: {},
463: {},
223: {} ..... // can be thousands of properties
}
Basically, the keys are IDs and the values are themselves objects. Now suppose I have an array of IDs that I pass into a function and I want that function to return an array of references to the values that match the IDs of the global object (ie. no deep copy). Something like this:
function GetReferences(TheArrayOfIDs) {
var TheArrayOfReferences = [];
return TheArrayOfReferences;
}
Now I know I can write a for loop that iterates over TheArrayOfIDs and that then loops over the object keys at each iteration but then that's a loop within a loop. So I'm looking for the fastest way of doing it, and jquery is available.
Basically, if TheArrayOfIDs = [323, 463, 223]; then TheArrayOfReferences =[TheFruit.323, TheFruit.463, TheFruit.223];
Thanks.
You don't need a second loop:
var results = [];
for (var i = 0; i < ids.length; i++)
results.push(fruits[ids[i]]);
You have to do only one loop as key look-up is built-in :
var TheArrayOfReferences = TheArrayOfIDs.map(function(id){return TheFruits[id]});
Something like that should work :
var i = 0, l = TheArrayOfIDs.length;
for (i = 0; i < l; i++)
TheArrayOfReferences.push(TheFruits[TheArrayOfIDs[i]]);
I usually script/program using python but have recently begun programming with JavaScript and have run into some problems while working with arrays.
In python, when I create an array and use for x in y I get this:
myarray = [5,4,3,2,1]
for x in myarray:
print x
and I get the expected output of:
5
4
3
..n
But my problem is that when using Javascript I get a different and completely unexpected (to me) result:
var world = [5,4,3,2,1]
for (var num in world) {
alert(num);
}
and I get the result:
0
1
2
..n
How can I get JavaScript to output num as the value in the array like python and why is this happening?
JavaScript and Python are different, and you do things in different ways between them.
In JavaScript, you really should (almost) always iterate over an array with a numeric index:
for (var i = 0; i < array.length; ++i)
alert(array[i]);
The "for ... in" construct in JavaScript gives you the keys of the object, not the values. It's tricky to use on an array because it operates on the array as an object, treating it no differently than any other sort of object. Thus, if the array object has additional properties — which is completely "legal" and not uncommon — your loop will pick those up in addition to the indexes of the "normal" array contents.
The variable num contains the array item's index, not the value. So you'd want:
alert(world[num])
to retrieve the value
The for var in... loop in JavaScript puts the keys in the variable instead of the actual value. So when using for var ... you should do something like this:
var world = [5, 4, 3, 2, 1];
for ( var key in world ) {
var value = world[key];
alert(key + " = " + value);
}
And note that this way of looping is best used when you're using objects instead of arrays. For arrays use the common:
for ( var i = 0, j = arr.length; i < j; i++ ) { ... }
Or if you're targeting modern browser you can use the forEach-method of arrays:
var arr = [1, 2, 3];
arr.forEach(function(num) {
alert(num);
});
The for...in loop loops over all key elements; not the values.
I would recommend you to use
for(var i=0; i<arr.length; i++){
alert(arr[i]);
}
When you use the in operator num becomes a key. So simply use this key to get a value out of the array.
var world = [5,4,3,2,1]
for (var num in world) {
alert(world[num]);
}
try this.
var world = [5,4,3,2,1]
for(var i=0;i<world.length;i++){
alert(world[i])
}
Because javascript in your case is printing the index of the element, not the value.
the result you got is just element index,if you want to get element value
your code should like this
var world = [5,4,3,2,1]
for (var num in world) {
alert(world[num]);
}
The for in iteration in JavaScript works only for the object data type. The way it works is that it lets you iterate over the attributes of an object. arrays are objects in JavaScript, but the for in only works on its attributes, not the array values.
For example you might define an array as such:
var arr = [1,2,3];
And you can assign attributes to this array, because it's actually an object:
arr.foo = "bar";
arr["1"] = 2;
Now when you use the for in iteration method you will be able to iterate over the attributes we just assigned above;
for(var i in arr) console.log(i);
To iterate over the actual array values you need to use the for(var i=0; i<arr.length; i++) construct.
Hope this helps.
In javascript it's advised to loop Arrays different from looping Objects. You are using an object loop, which may return unexpected result (for instance if the Array.prototype was extended with custom methods you would iterate those too, and it does't guarantee the order of the array is preserved). There are many ways to loop through an array, using it's index:
// regular
var arr = [1,2,3,4,5]
,i
;
for (i=0;i<arr.length;i++) {
console.log(arr[i]);
}
// using while
var arr = [1,2,3,4,5]
,i = 0
;
while ((i = i + 1)<arr.length) {
console.log(arr[i]);
}
// using while reversed
var arr = [1,2,3,4,5]
,i = arr.length
;
while ((i = i - 1) > -1) {
console.log(arr[i]);
}
Note: Why not use i++ or i--? To avoid confusion, index out of range-errors and to satisfy JSLint
Considering this data structure:
var vehicles = [
[ "2011","Honda","Accord" ],
[ "2010","Honda","Accord" ],
.....
];
Looping through each vehicles item, is there a way to reassign the array elements to individual variables all in one shot, something like:
for (i = 0; i < vehicles.length; i++) {
var(year,make,model) = vehicles[i]; // doesn't work
.....
}
... I'm trying to get away from doing:
for (i = 0; i < vehicles.length; i++) {
var year = vehicles[i][0];
var make = vehicles[i][1];
var model = vehicles[i][2];
.....
}
Just curious since this type of thing is available in other programming languages. Thanks!
Now it is possible using ES6's Array Destructuring.
As from Docs:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Consider the following example:
let [a, b, c] = [10, 20, 30];
console.log(a); // output => 10
console.log(b); // output => 20
console.log(c); // output => 30
As with your data, .forEach() method can also be used for iterating over array elements along with Array Destructuring:
let vehicles = [
[ "2011","Honda","Accord" ],
[ "2010","Honda","Accord" ]
];
vehicles.forEach(([year, make, model], index) => {
// ... your code here ...
console.log(`${year}, ${make}, ${model}, ${index}`);
});
References:
Array Destructuring
Array.prototype.forEach()
Arrow Functions
Template Literals
No unfortunately there is not a method to do this currently XBrowser. (that I'm aware of).
Relatively soon it's possible cross browser, see link:
https://developer.mozilla.org/en/New_in_JavaScript_1.7
(In PHP there is "list" which will do exactly what you wish, nothing similar XBrowser for javascript yet)
Of course relatively soon could mean anything etc. (Thanks Felix for pointing out my errors in this)
edit: This is now available see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring
Probably the closest you'll currently get in javascript is to eliminate the redundant var and separate the statements with a comma separator.
for (i = 0; i < vehicles.length; i++) {
var year = vehicles[i][0], make = vehicles[i][1], model = vehicles[i][2];
.....
}
or you could shorten it a bit more like this:
for (i = 0; i < vehicles.length; i++) {
var v = vehicles[i], year = v[0], make = v[1], model = v[2];
.....
}
The closest alternative that I could think of is using a function and using apply() to call it. Passing an array, it would get passed as each argument.
function vehicle(year, make, model) {
// do stuff
}
for (i = 0; i < vehicles.length; i++) {
vehicle.apply (this, vehicles[i]);
}
Or an anonymous function:
for (i = 0; i < vehicles.length; i++) {
(function(year, make, model) {
// do stuff
}).apply(this, vehicles[i]);
}
Unpacking array into separate variables in JavaScript
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from objects,into distinct variables.
let array = [2,3];
[a,b] = array;// unpacking array into var a and b
console.log(a); //output 2
console.log(b); //output 3
let obj = {name:"someone",weight:"500pounds"};
let {name,weight} = obj; // unpacking obj into var name and weight
console.log(name);// output someone
console.log(weight);//output 500pounds
Source