$.each() over Key value pair array - javascript

I've created my array as following:
var test = [];
test['pizza'] = 4;
test['pudding'] = 6;
I'm used to use $.each to loop over my array and print out the values and indexes. I'm doing this as following:
$.each(test, function (index, value){
console.log(value);
});
Yet somehow it does only print [].
How would one loop through an array as mine to print out the values 4 and 6?

each will only iterate over iterable properties of the array, pizza and pudding are not iterable properties.
As you require the key-value pair, declare the variable as object.
var test = {};
test['pizza'] = 4;
test['pudding'] = 6;

You don't need jQuery to iterate through a Javascript array, just use for.
var test = [];
test['pizza'] = 4;
test['pudding'] = 6;
for (var k in test) {
if (test.hasOwnProperty(k)) {
console.log('Key: ' + k + ' Value: ' + test[k]);
}
}
// Key: pizza Value: 4
// Key: pudding Value: 6
You don't need to declare test as an object for this (suggested in other answers), array is fine.
By using for you are improving performance of your application. See here.
In both Firefox and Chrome, the for loop is well over 100x faster than
the others.

you might want to choose what happens to serve your needs. I guess you were trying to get a array of objects which will look something like [{},{},{},{}]

Here test is an object(Associative array), not an array so you need to declare it as javascript object
var test = {};
test['pizza'] = 4;
test['pudding'] = 6;
$.each(test, function (index, value){
console.log(value);
});

Related

Creating array with function and returning its name in javascript

I am trying to create a function that generates empty arrays.
Problems:
I don't know how to show the name of the array in console.log.
how to make the array and array's name accessible in a global scope
function arrayCreator (arrName){
arrName = [];
console.log(arrName.name() + ' : ' arrName);
}
P.S. arrName.name() doesn't work, of course. It is more like a placeholder.
This is one possible implementation that may achieve the result you want. The function stores the arrays in an object. You can access the array names on a global scope using Object.keys(myobject) . Of course I just made a loop to create some random array names and call the function multiple times. I'm not sure how your application will be getting array names.
var arrObject = {};
function arrayCreator (arrName){
arrObject[arrName] = [];
}
for( i = 0; i < 10; i++)
{
arrayName = "myArray" + i;
arrayCreator(arrayName);
}
console.log(arrObject);
console.log(Object.keys(arrObject));

for in loop behaving strangely in javascript

var friends=['2','3'];
console.log(friends);
var rooms=[];
for(var friend in friends){
var room = 'userid'+friend+'friends';
console.log(room);
rooms.push(room);
}
console.log(rooms);
this outputs
[ '2', '3' ]
userid0friends
userid1friends
[ 'userid0friends', 'userid1friends' ]
3 is neglected entirely, and it behaves even more strangely on my node.js server
friend here is the index of your array, not the value at the index
var room = 'userid'+friends[friend]+'friends';
Plus when looping through an array I don't recommend to use for..in loops, you can use Array.prototype.map or plain for loop with the length of your array
Array map example:
var friends=['2','3'];
console.log(friends);
var rooms= friends.map(function (friend, index) {
return 'userid' + friend + 'friends';
});
console.log(rooms);
Plain for loop:
var friends=['2','3'];
console.log(friends);
var rooms=[];
for (var i = 0, l = friends.length; i < l; ++i) {
var room = 'userid' + friends[i] + 'friends';
console.log(room);
rooms.push(room);
}
console.log(rooms);
The for in structure is used to loop the object, for key in object, key is the property name of the object, when used for an array, key will be the array index.
You could use .map to get your result:
var friends=['2','3'];
var rooms = friends.map(function(e) {
return 'userid'+e+'friends';
});
A for in loop is used to enumerate objects. You are trying to iterate over an array. A better technique for iterating would be a regular for loop or the Array.forEach() method.
In a for in loop, the variable contains the key, not the value. To get the value, use the key:
for(var i in friends){
var friend = friends[i];
...
}
But, again, this enumerates an object, including any properties besides the array elements. This means that if any code adds a method to Array.prototype, that method will also be enumerated. Using .forEach() is better:
friends.forEach(function (friend, i) {
...
});
Better yet, since you are trying to create a new Array based on the contents of another, use Array.map(). That is exactly what it's for.
var rooms = friends.map(function (friend, i) {
return 'userid'+friend+'friends';
});

sum index in JavaScript foreach

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.

JavaScript Array

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

JavaScript: Split array into individual variables

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

Categories