传统for循环和for循环中的Javascript破坏问题

传统for循环和for循环中的Javascript破坏问题,javascript,ecmascript-6,Javascript,Ecmascript 6,假设我有一个点数组=[[1,3],-2,2],它们代表x,y坐标 我想在点[x,y]上访问这些值(两点的距离)。我只是无法理解这两种方法是如何不同的 为什么我可以访问一个hash-maps值,而下一个值是未定义的 函数获取距离1(点){ const lookup=新映射(); //用一个for of进行破坏 用于(点的常数[x,y]{ 设距离=Math.sqrt((x**2)+(y**2)) lookup.set([x,y],距离) } //当我尝试从哈希映射中检索值时,我将无法访问数组的值

假设我有一个点数组=[[1,3],-2,2],它们代表x,y坐标

我想在点[x,y]上访问这些值(两点的距离)。我只是无法理解这两种方法是如何不同的

为什么我可以访问一个hash-maps值,而下一个值是未定义的

函数获取距离1(点){
const lookup=新映射();
//用一个for of进行破坏
用于(点的常数[x,y]{
设距离=Math.sqrt((x**2)+(y**2))
lookup.set([x,y],距离)
}
//当我尝试从哈希映射中检索值时,我将无法访问数组的值
返回查找;
}
函数getDistances2(点){
const lookup=新映射();
//用传统的for循环进行破坏
for(设i=0;i3.1622776601683795;

console.log(distance1.get(坐标[0])//未定义
之所以
getDistances1
不起作用,是因为您在此处创建了单独的
x
y
变量:

for (const [x, y] of points) {
然后在此处创建一个新数组:

lookup.set([x,y], distance)
但是您正试图使用
点中的数组查找信息。信息不是存储在该数组下,而是存储在新数组下

您可以这样做(请参见
***
注释):

function getDistances1(points) {
    const lookup = new Map(); 
    // Destructing with a for of
    for (const point of points) {    // *** Use the array from `points
        const [x, y] = point;        // *** Convenient destructuring
        let distance = Math.sqrt((x**2) + (y**2))
        lookup.set(point, distance); // *** Store keyed by the array
    }
  
    return lookup; 
}