Reputation: 24061
I have an array:
var fileMetaData = [];
In a loop I want to push things to the array:
$('#gallery-manager-add-form .galleryImage').each(function(){
fileMetaData.push(myTestArray);
});
For testing myTestArray is:
var myTestArray = new Array(2);
myTestArray['a'] = 'foo';
myTestArray['b'] = 'bar';
The problem is, when I get the contents of the array, it's just a comma (,).
Any ideas where I am going wrong?
Upvotes: 0
Views: 193
Reputation: 1013
this should work
$('#gallery-manager-add-form .galleryImage').each(function(){
fileMetaData.push(myTestArray[0],myTestArray[1]);
});
1 dimensional array http://jsfiddle.net/Gs6ZU/
2 dimensional array http://jsfiddle.net/fY9S5/1/
Upvotes: 0
Reputation: 40383
When you're assigning values to myTestArray['a']
and myTestArray['b']
, you're not pushing them into the array, but rather assigning the values to properties of the object. To treat the items as values in an array, you'd need to use the integer indexes, or just push
them:
myTestArray[0] = 'foo';
myTestArray.push('bar');
But the other part, where you're pushing into the fileMetaData
array - if you're trying to push both items from myTestArray
, you'd need to do that differently - if you push one array into another, you're pushing the array, not the items. You'd need to either loop through one at a time and push them that way, or use something like concat
to merge the arrays.
Upvotes: 0
Reputation: 3669
Arrays use numerical keys. You've used "a" and "b".
Initialise it like this:
var myTestArray = ['foo', 'bar'];
Alternatively, use this to keep your code almost the same:
var myTestArray = new Array(2);
myTestArray[0] = 'foo';
myTestArray[1] = 'bar';
Upvotes: 1
Reputation: 382092
That's because you're confusing arrays and objects (which you should use).
If your keys are 'a'
and 'b'
, use
var myTestArray = {};
myTestArray['a'] = 'foo';
myTestArray['b'] = 'bar';
If you really want to use an array, use
var myTestArray = [];
myTestArray.push('foo'); // no explicit key
myTestArray.push('bar');
You saw just a comma because, the standard representation of an array doesn't look for properties, so you were printing the equivalent of [[],[]].toString()
which is ","
.
Upvotes: 4