gpt4 book ai didi

javascript - 为 JavaScript 函数参数定义对象默认值

转载 作者:行者123 更新时间:2023-11-30 13:21:48 24 4
gpt4 key购买 nike

我有一个小类可以扩展 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());
}

我想做的是将选项参数定义为一个包含小时、分钟和秒的对象,并将其添加到时间中。例如,

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) {})我更喜欢像处理参数一样 - 作为一个对象 - 而不是为每个值传递单独的参数。

谢谢!

最佳答案

您可以制作一个小迭代器来检查对象属性:

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....
};

关于javascript - 为 JavaScript 函数参数定义对象默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10017961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com