【问题标题】:object destructing with paramaters on function使用函数参数进行对象解构
【发布时间】:2019-04-17 21:18:26
【问题描述】:

如果我有以下 ES6 方法:

function myClothes([first, second, third]) {
  return {
    first: first,
    second: second,
    third: third
  }
} 

如何在控制台窗口中打印出“运动鞋裤子衬衫”?我尝试了以下方法,但仍然没有解决方案:

console.log(myClothes({
  ['first']:'sneakers',
  ['second']:'pants',
  ['third']:'shirt'
}));

我做错了什么?

非常感谢!

【问题讨论】:

    标签: javascript arrays function object ecmascript-6


    【解决方案1】:

    首先,将您的函数更改为使用对象解构。然后在函数内部使用一个简单的console.log 语句:

    function myClothes({first, second, third}) {
      console.log([first, second, third].join(" "));
      return {
        first: first,
        second: second,
        third: third
      }
    }
    
    console.log(myClothes({
      ['first']:'sneakers',
      ['second']:'pants',
      ['third']:'shirt'
    }));
    .as-console-wrapper { max-height: 100% !important; top: auto; }

    【讨论】:

    • @klewis 所以对象是{ first: "sneakers" } 位,它是从您的函数返回的。对于[first, second, third] 中的console.log,您是否希望它们用sneakers pants shirt 之类的空格连接?
    • @klewis 我已经编辑了我的答案,现在对你有用吗?
    • 啊我现在明白了。我总是可以在我的函数内部打印到控制台,而不是在每次调用时打印到控制台之外。另外我不知道加入。感谢 Jack 在这方面的课程!
    • 没问题@klewis,总是乐于提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 2017-11-14
    • 2019-04-18
    • 2022-06-29
    • 1970-01-01
    相关资源
    最近更新 更多