【问题标题】:Accolades around an argument of a (.map()) function [duplicate]围绕(.map())函数的参数获得赞誉[重复]
【发布时间】:2020-11-02 10:28:54
【问题描述】:

我在 Stack Overflow (this answer) 上查看其他人的代码并看到一些奇怪的东西。我以前从未见过的东西。另外,我找不到任何文档。

此代码(基于答案中的代码)是一个示例:

let data = [
  { records: "productId*amount*tax1*tax2*tax3", id: 467 },
  { records: "111*2000*10*12*13", id: 278 },
  { records: "113*3000*10**", id: 787 }
];

let ids = data.map(({ id }) => console.log(id));

显然,当您使用({id}) 作为回调的参数时,该参数不包含数组中的项,而是数组中项(对象)的该属性的值。

有人知道这里发生了什么吗?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    是的,它叫destructuring

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

    他从参数对象中解构了属性id

    【讨论】:

      【解决方案2】:

      这适用于任何对象,而不仅仅是在地图数组方法中。假设您有一个对象数据。

      const data= {name: "price", value: 111};
      

      您可以通过 2 种方式访问​​该值。

      const value = data.value
      

      一样
      const {value} = data
      

      【讨论】:

        【解决方案3】:

        是的,在 ES6 及更高版本中,引入了解构功能。在这种情况下,传递给 map 函数的参数是数据数组中对象的属性 id。请看下面的场景:

        // create an object with id and label
        const originalObj = { id: 1, label: 'First Item' };
        /* create values from keys in object done via destructuring.  
           Here we get the values of the keys in the object by enclosing the 
           keys in the declaration 
           and set it equal the object
           with the properties. This will create 
           variables id and label and set them to 
           values 1 and 'First Item'.  This is what is happening in the map 
           call 
        */
        const { id, label } = originalObj;
        

        【讨论】:

          【解决方案4】:

          我已经知道解构(虽然显然不完全)。由于其他答案要么不是关于函数参数,要么只是给出一个链接,我会自己回答。

          在 developer.mozilla.org 上,它被称为 从作为函数参数传递的对象中解包字段。举个很清楚的例子:

          const user = {
            id: 42,
            displayName: 'jdoe',
            fullName: {
              firstName: 'John',
              lastName: 'Doe'
            }
          };
          
          function userId({id}) {
            return id;
          }
          
          function whois({displayName, fullName: {firstName: name}}) {
            return `${displayName} is ${name}`;
          }
          
          console.log(userId(user)); // 42
          console.log(whois(user));  // "jdoe is John"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-03-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-09-27
            相关资源
            最近更新 更多