函数参数内的自动数组解构?

Automatic Array destructuring within function parameter?

function getValues(param=[width, height]) {
   return `Width= ${width}, Height = ${height}`;
  }

上面的代码不起作用,因为"width"和"height"没有在函数体内定义

但是,下面的函数定义工作正常,我不太清楚为什么数组参数会自动解构为下面的元素,而在上面的例子中却不是这样。

 function getValues([width, height]) {
   return `Width= ${width}, Height = ${height}`;
  }

如有任何澄清,我将不胜感激。谢谢。

  • 第一个函数将 中的数组值分配给 param 函数参数
  • 第二个函数只有参数作为值。

你应该试试

function getValues(param=[width, height]) {
   return `Width= ${param[0]}, Height = ${param[1]}`;
  }

两个功能都很好。在第二个中,数组的第一个值被分配给 width 变量,第二个被分配给函数范围内的 height 变量。记得使用数组调用函数。

function getValues([width, height]) {
  return `Width= ${width}, Height = ${height}`;
}

getValues([100,200]); // 'Width= 100, Height = 200'

在参数中使用 =,基本上是在缺少参数 (Default parameters) 的情况下设置默认值。一次,您调用缺少参数或 undefined 作为参数的函数,默认值针对参数设置。在你的例子中,如果你传递任何参数,默认值 [width, height] 将被忽略,如果你不这样做, Uncaught ReferenceError 将被抛出,因为宽度和高度不存在(假设没有全局定义或在功能范围)。

下面将为您提供宽度和高度的值,因为第一个参数分配给 width,第二个参数分配给 height

function getValues(width, height, param=[width, height]) {
   console.log(param); // [5,6]
   return `Width= ${width}, Height = ${height}`;
}
  
console.log(getValues(5,6));

But, the function definition below works fine and I am not quite clear why the array parameters are automatically destructured to its elements below, while it doesn't so in the above case.

这符合Destructuring的规则。如果参数是数组,则可以根据索引将它们分配到不同的变量中。例如这里数组中的第一个值将分配给 width,第二个值将分配给 height

function getValues([width, height]) {
  return `Width= ${width}, Height = ${height}`;
}

console.log(getValues([5, 6]));