Reputation: 3654
This is a really stupid question, but I'm just drawing a blank here...
What type of variable declaration is this:
var s1 = [1,2,3,4]
Also, How can I construct a variable like this from multiple objects when the amount of those objects is unknown. This is what I came up with, which doesn't work.
var s1 = [];
for(x in data[i].uh) {
s1 += data[i].uh[x];
}
Upvotes: 0
Views: 655
Reputation: 10047
var s1 = [1,2,3,4]
is an array declaration of four integers using "Array Literal Notation"
You don't need a loop to copy the array, simply do this:
var s1 = data.slice(0);
or in your example you might want this:
var s1 = data[i].uh.slice(0);
Read more about copying arrays here: http://my.opera.com/GreyWyvern/blog/show.dml/1725165
"The slice(0) method means, return a slice of the array from element 0 to the end. In other words, the entire array. Voila, a copy of the array."
Upvotes: 2
Reputation: 57709
s1
is an array, it's a proper Javascript object with functions.
var s1 = [];
is the recommend way to create an array. As opposed to:
var s1 = new Array();
(see: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays)
To add items to an array use s1.push(item)
so your code would be:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
As a side note, I wouldn't recommend using for-in, at least not without checking hasOwnProperty.
Upvotes: 2
Reputation: 16139
That is an array. To add to arrays you would use Array.push(). For example:
var s1 = [];
s1.push(1);
s1.push(2);
Upvotes: 1
Reputation: 142911
This
var s1 = [1,2,3,4]
is an array declaration.
To add an element to an array, use the push
method:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
Upvotes: 2
Reputation: 50177
That is called an Array
, which can be declared with new Array()
or by using the array literal []
as in your example. You can use the Array.push()
method (see docs) to add a new value to it:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
Upvotes: 2
Reputation: 490143
It's declaring a local variable with an Array
with 4 members.
If you want to append to an Array
, use the push()
method.
Upvotes: 1