我有一个嵌套的数组,其中包含一些坐标。我正在尝试循环嵌套数组并记录每个坐标的值。
我可以在Python中使用它,但是我需要在JavaScript中使用它。这是它在python中的工作方式:
list_of_coordinates = [(100, 98), (200, 78)]
for i in list_of_coordinates:
x_coord = i[0]
y_coord = i[1]
print(x_coord, y_coord)
上面的输出是:
100 98
200 78
当我尝试使用Javascript执行此操作时,得到的输出为0和1 ...而不是实际的坐标值。
let listOfCoordinates = [[100, 0], [200, 1]];
for (const i in listOfCoordinates) {
let xCoord = i[0];
let yCoord = i[1];
console.log(xCoord, yCoord);
}
此输出为
0 undefined
1 undefined
答案 0 :(得分:3)
您应使用for..of
代替以下内容:
let listOfCoordinates = [[100, 0], [200, 1]];
for (const i of listOfCoordinates) {
let xCoord = i[0];
let yCoord = i[1];
console.log(xCoord, yCoord);
}
请参阅文档:
for...of
语句创建一个循环,循环访问可迭代对象,这些对象包括:内置String,Array,类似数组的对象(例如,参数或NodeList),TypedArray,Map,Set和用户定义的可迭代对象。它使用对象的每个不同属性的值调用带有要执行的语句的自定义迭代挂钩。
答案 1 :(得分:0)
正确的方法,如果您想继续使用for...in:
const listOfCoordinates = [[100, 0], [200, 1]];
for (let i in listOfCoordinates) {
let xCoord = listOfCoordinates[i][0];
let yCoord = listOfCoordinates[i][1];
console.log(xCoord, yCoord);
}
因为您将变量“ i”命名为“ index”,所以它通常是“ index”的缩写,所以我想您希望它成为一个索引,使用“ in”形式。
for...of表单返回值。可以这样写:
const listOfCoordinates = [[100, 0], [200, 1]];
for (let coord of listOfCoordinates) {
let xCoord = coord[0];
let yCoord = coord[1];
console.log(xCoord, yCoord);
}
答案 2 :(得分:0)
forEach
方式,对输入进行解构。
let listOfCoordinates = [[100, 0], [200, 1]];
listOfCoordinates.forEach(([xCoord, yCoord]) => console.log(xCoord, yCoord));
答案 3 :(得分:0)
您可以将for ... of
statement和destructuring assignment带入想要的变量。
let listOfCoordinates = [[100, 0], [200, 1]];
for (const [xCoord, yCoord] of listOfCoordinates) {
console.log(xCoord, yCoord);
}