我试图获取 JavaScript 数组中所有元素的列表,但我注意到使用 array.toString
并不总是显示数组的所有内容,即使当数组的某些元素已被初始化时。有没有办法在 JavaScript 中打印数组的每个元素,以及每个元素的相应坐标?我想找到一种方法来打印数组中已定义的所有坐标的列表,以及每个坐标的相应值。
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
最佳答案
实际上,当您使用坐标 [[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]);
});
关于javascript - 获取 JavaScript 数组中所有元素的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15354100/