Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of all elements in a JavaScript array

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
like image 690
Anderson Green Avatar asked Mar 12 '13 05:03

Anderson Green


People also ask

How do I see all the elements in an array?

The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements.

How do you access the values within an array?

Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name. Array subscripts must be of integer type.

How do you get all Li in UL?

In JavaScript, you can use the . getElementsByTagName() method to get all the <li> elements in <ul>. In-addition, you can use the . querySelectorAll() method also to get all the <li>.

How do I find an element in an array of arrays?

Use forEach() to find an element in an array The Array. prototype. forEach() method executes the same code for each element of an array. The code is simply a search of the index Rudolf (🦌) is in using indexOf.


2 Answers

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/

like image 197
Imran Qadir Baksh - Baloch Avatar answered Nov 12 '22 06:11

Imran Qadir Baksh - Baloch


Use type 'object' instead 'array' for coordinates

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(JSON.stringify(coordinates));

http://jsfiddle.net/5eeHy/

like image 22
Latikov Dmitry Avatar answered Nov 12 '22 07:11

Latikov Dmitry