javascript - 对象属性的展开运算符 (...) 的等价物是什么?

标签 javascript ecmascript-6

我正在构建一个笔记应用程序,需要一种方法将用户花费的时间传递给存储它的构造函数。这是目的地:

var NoteTime = function(minute, hour, day, month, year) {
    var d = new Date();
    this.millisec = d.getMilliseconds();
    this.minute = minute || d.getMinutes();
    this.hour = hour || d.getHours();
    this.day = day || d.getDay();
    this.month = month || d.getMonth();
    this.year = year || d.getUTCFullYear();
}

var gatheredTime = {
    minute: null,
    hour: null,
    day: null,
    month: null,
    year: null
}

我知道我可以像这样度过gatheredTime

var storeResult = new NoteTime(gatheredTime[prop1], gatheredTime[prop2]....etc)

但我想使用更少的代码并像传递数组一样传递值:

var storeResult = new NoteTime(...gatheredTime)

是的,我可以将它转换为数组,但我想知道是否有更好的方法。

最佳答案

使用Destructuring assignment

var NoteTime = function (gatheredTime) {
    let {minute, hour, day, month, year} = gatheredTime;

var NoteTime = function(gatheredTime) {
  let {
    minute, hour, day, month, year
  } = gatheredTime;
  console.log(minute, hour, day, month, year);
  // code here
};

var gatheredTime = {
  minute: 10,
  hour: 5,
  day: 9,
  month: 8,
  year: 2016
};

NoteTime(gatheredTime);


或者,参数可以在arguments中直接销毁。

var NoteTime = function ({minute, hour, day, month, year}) {

关于javascript - 对象属性的展开运算符 (...) 的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38847794/

相关文章:

javascript - "const something = () => ({..."箭头函数模式

javascript - 在 Chrome V8 中实例化从 Object 扩展的类时,super() 不传递参数

javascript - 如何使用 JavaScript 仅针对 Internet Explorer 11?

javascript - 我应该用什么来代替 ng-repeater

javascript - 将 HTML 存储在 JS 变量中但保留 HTML 变量

Javascript数组减少将数组转换为具有整数键的对象

javascript - 更改正在运行的处理动画的帧速率

javascript - 如何检测图像文件是否存在于我的案例中?

javascript - 迭代对象列表但插入计算值

javascript - Typescript 将 es6 .js 依赖转译为 es5