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];
}
-
that's an array. developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…KJYe.Name– KJYe.Name2011年04月28日 00:32:51 +00:00Commented Apr 28, 2011 at 0:32
6 Answers 6
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."
2 Comments
var foo = [1,2,3,4,5]; alert(foo[2]); /* Returns 3 */ var bar = foo.slice(0); alert(bar[2]); /* Returns 3 */ bar[2] = 0; alert(bar[2]); /* Returns 0 */ alert(foo[2]); /* Returns 3 */ w3schools.com/jsref/jsref_slice_array.asp 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]);
}
1 Comment
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]);
}
Comments
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.
Comments
It's declaring a local variable with an Array with 4 members.
If you want to append to an Array, use the push() method.
Comments
That is an array. To add to arrays you would use Array.push(). For example:
var s1 = [];
s1.push(1);
s1.push(2);