简体   繁体   English

解构对象和默认参数

[英]Destructuring Objects and default parameters

I have a problem to solve involving default parameters and object destructuring.我有一个问题需要解决,涉及默认参数和对象解构。 I have an object 'product' with this shape:我有一个具有这种形状的对象“产品”:

{
     name: "Slip Dress",
     priceInCents: 8800,
     availableSizes: [ 0, 2, 4, 6, 10, 12, 16 ]
   }

Here is my code so far, but I am receiving an error that 'availableSizes' is not iterable.到目前为止,这是我的代码,但我收到了“availableSizes”不可迭代的错误。 Can someone help me correct this code?有人可以帮我更正此代码吗?

I have tried adjusting the default parameters in my function and I have moved my return statements to no avail.我已尝试调整函数中的默认参数,但已将返回语句移到无济于事。

function checkIfSizeIsAvailable(product = {availableSizes:[]}, size = 0) {
  // let availableSizes = product;
  let foundSize = "";
  for (let sizeCheck of product.availableSizes) {
    if (sizeCheck === size) {
      foundSize = size;
    }
  }
  if (foundSize === ""){
    return false;
  } else {
    return true;
  }
  //for (let i = 0; i < sizes.length; i++) {
  // return false;
}

As VLAZ mentioned in a comment, you can pass an object without an availableSizes field and it'll cause that error.正如 VLAZ 在评论中提到的,您可以传递一个没有availableSizes字段的对象,它会导致该错误。

Destructuring happens when your variables together form an object/array on the left-hand size of the assignment:当您的变量一起在赋值的左侧大小上形成一个对象/数组时,就会发生解构:

function checkIfSizeIsAvailable(product = {availableSizes:[]}, size = 0) {
  // ^ Because of the default parameter, product always exists
  // Now we actually destructure with a default value for missing fields
  const { availableSizes = [] } = product;
}

or more compact:或更紧凑:

function checkIfSizeIsAvailable({ availableSizes = [] } = {availableSizes:[]}, size = 0) {

}

Mind that this does not defend against non-array values, or even falsy values.请注意,这并不能抵御非数组值,甚至是虚假值。 A user can pass { availableSizes: false } and your availableSizes would also be false .用户可以传递{ availableSizes: false }并且您的availableSizes也将为false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM