简体   繁体   English

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

[英]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. 我正在尝试获取JavaScript数组中所有元素的列表,但我注意到使用array.toString并不总是显示数组的所有内容,即使数组的某些元素已经初始化也是如此。 Is there any way to print each element of an array in JavaScript, along with the corresponding coordinates for each element? 有没有办法在JavaScript中打印数组的每个元素,以及每个元素的相应坐标? 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/ 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

Actually when you use coordinates[[0, 0, 3]] then this means coordinates object with [0, 0, 3] as key. 实际上当你使用坐标[[0,0,3]]时,这意味着以[0,0,3]作为关键坐标对象。 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/ http://jsfiddle.net/GwgDN/17/

Use type 'object' instead 'array' for coordinates 使用类型'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/ http://jsfiddle.net/5eeHy/

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

use join function to get all elements of array.use following code 使用join函数获取array.use的所有元素以下代码

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

Look at coordinates in the debugger and you will see that you have set the properties [0,0,3,5] and [0,0,3] of the object coordinates. 查看调试器中的坐标,您将看到已设置对象坐标的属性[0,0,3,5]和[0,0,3]。 That is although coordinates is an array you are not using it as an array. 这是虽然坐标是一个数组,但你没有将它用作数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM