我正在尝试获取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
Run Code Online (Sandbox Code Playgroud)
实际上当你使用坐标[[0,0,3]]时,这意味着以[0,0,3]作为关键坐标对象.它不会将元素推送到数组,而是将属性附加到对象.所以使用循环遍历对象的这一行.看到这个,用于通过物体的属性等方式来循环,
Object.keys(coordinates).forEach(function(key) {
console.log(key, coordinates[key]);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46431 次 |
| 最近记录: |