我正在构建一个记笔记应用,并且需要一种方法将用户所花费的时间传递给存储它的构造函数。这是目的地:
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)
是的我可以将它转换为数组,但我想知道是否有更好的方法。
答案 0 :(得分:4)
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);

或者,可以在参数中直接破坏参数。
var NoteTime = function ({minute, hour, day, month, year}) {
答案 1 :(得分:0)
您可能需要通过添加[Symbol.iterator]
方法将对象转换为可迭代,然后您可以在标准JS对象上使用for of
循环或扩展运算符。例如;
var o = {a:1,b:2,c:3},
a = [];
o[Symbol.iterator] = function*(){
var ok = Object.keys(this),
i = 0;
while (i < ok.length) yield this[ok[i++]];
};
for (var value of o) console.log(value);
// or you can even do like
a = [...o];
console.log(a);
您可以在构造函数中添加符号迭代器,以便所有实例化的对象都是可迭代的。