获取JavaScript数组中所有元素的列表

时间:2013-03-12 05:40:40

标签: javascript arrays

我正在尝试获取JavaScript数组中所有元素的列表,但我注意到使用array.toString并不总是显示数组的所有内容,即使在某些元素中也是如此。数组已初始化。有没有办法在JavaScript中打印数组的每个元素,以及每个元素的相应坐标?我想找到一种方法来打印已在数组中定义的所有坐标的列表,以及每个坐标的相应值。

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

5 个答案:

答案 0 :(得分:7)

实际上当你使用坐标[[0,0,3]]时,这意味着以[0,0,3]作为关键坐标对象。它不会将元素推送到数组,而是将属性附加到对象。所以使用循环遍历对象的这一行。 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/

答案 1 :(得分:3)

使用类型'object'代替'array'作为坐标

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/

答案 2 :(得分:1)

for (i=0;i<coordinates.length;i++)
{
document.write(coordinates[i] + "<br >");
}

答案 3 :(得分:1)

使用join函数获取array.use的所有元素,代码如下

for (var i in coordinates)
{
    if( typeof coordinates[i] == 'string' ){
        console.log( coordinates[i] + "<br >");
    }
}

答案 4 :(得分:0)

查看调试器中的坐标,您将看到已设置对象坐标的属性[0,0,3,5]和[0,0,3]。这是虽然坐标是一个数组,但你没有将它用作数组。