我有一个在JavaScript中扩展Date对象的小类。一种方法只返回UTC中的当前日期。
Date.prototype.nowUTC = function(options) {
var now = new Date();
return new Date(now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds());
}
我想要做的是将options参数定义为包含小时,分钟和秒的对象,这些对象将被添加到时间中。例如,
Date.prototype.nowUTC = function(options) {
var now = new Date();
return new Date(now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours() + options.hours,
now.getUTCMinutes() + options.minutes,
now.getUTCSeconds()) + options.seconds;
}
有没有办法预先定义这些值,所以在添加或设置默认值之前,我不必检查它是否已定义? (例如function(options = {'hours' : null, 'minutes' : null, 'seconds' : null) {}
)我更喜欢将parmeter像 - 作为一个对象 - 而不是为每个值传递单独的参数。
谢谢!
答案 0 :(得分:2)
您可以创建一个小迭代器来检查对象属性:
Date.prototype.nowUTC = function(options) {
// Object holding default values for this function
var defaults = {
"hours": <default>,
"minutes": <default>,
"seconds": <default>
};
// Iterate over the options and set defaults where the property isn't defined.
for (var prop in defaults) {
options[prop] = options[prop] || defaults[prop];
// Note: if options would contain some falsy values, you should check for undefined instead.
// The above version is nicer and shorter, but would fail if, for example,
// options.boolVal = false
// defaults.boolVal = true
// the defaults would always overwrite the falsy input property.
options[prop] = typeof options[prop] !== 'undefined' ? options[prop] : defaults[prop];
}
var now = new Date();
// Rest of your function, using the options object....
};
答案 1 :(得分:1)
Object.assign
是为对象分配值并使用输入扩展该对象的最简单方法。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
所以在您的情况下:
Date.prototype.nowUTC = function(options) {
var defaults = {
hours: 0,
minutes: 0,
seconds: 0,
};
var now = new Date();
options = Object.assign(defaults, options);
return new Date(now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours() + options.hours,
now.getUTCMinutes() + options.minutes,
now.getUTCSeconds()) + options.seconds;
}