Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  165] [ 6]  / answers: 1 / hits: 69809  / 11 Years ago, tue, march 12, 2013, 12:00:00

I'm trying to obtain a list of all elements that are in a JavaScript array, but I've noticed that using array.toString does not always show all the contents of the array, even when some elements of the array have been initialized. Is there any way to print each element of an array in JavaScript, along with the corresponding coordinates for each element? I want to find a way to print a list of all coordinates that have been defined in the array, along with the corresponding values for each coordinate.



http://jsfiddle.net/GwgDN/3/



var coordinates = [];
coordinates[[0, 0, 3, 5]] = Hello World;

coordinates[[0, 0, 3]] = Hello World1;

console.log(coordinates[[0, 0, 3]]);
console.log(coordinates[[0, 0, 3, 5]]);
console.log(coordinates.toString()); //this doesn't print anything at all, despite the fact that some elements in this array are defined

More From » arrays

 Answers
31

Actually when you use coordinates[[0, 0, 3]] then this means coordinates object with [0, 0, 3] as key. It will not push an element to array but append a property to the object. So use this line which loop through objects. See this for other ways to loop through object properties,



Object.keys(coordinates).forEach(function(key) {
console.log(key, coordinates[key]);
});


http://jsfiddle.net/GwgDN/17/


[#79656] Monday, March 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devonw

Total Points: 311
Total Questions: 116
Total Answers: 111

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;