下划线“默认”从头开始
我一直在尝试从 underscore.js 重写 _.defaults 方法,但不断收到此错误:
应该将源属性复制到目标对象中未定义的属性‣ AssertionError:预期 { a: 'existing' } 深度等于 { a: 'existing', b: 2, c: 3, d: 4 }
这是缺少的条件:
- 应将源属性复制到目标对象中未定义的属性,并应返回目标对象
和我的代码:
_.defaults = function (destination, source) {
Object.keys(destination).forEach(key => {
if (destination[key] === undefined || destination[key] === null) {
destination[key] = source[key];
}
})
return destination;
};
I've been trying to rewrite the _.defaults method from underscore.js and I keep getting this error:
should copy source properties to undefined properties in the destination object‣
AssertionError: expected { a: 'existing' } to deeply equal { a: 'existing', b: 2, c: 3, d: 4 }
Here's the missing conditions:
-should copy source properties to undefined properties in the destination object and should return the destination object
and my code:
_.defaults = function (destination, source) {
Object.keys(destination).forEach(key => {
if (destination[key] === undefined || destination[key] === null) {
destination[key] = source[key];
}
})
return destination;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
_.defaults
中的想法是源对象中的键可能会丢失完全在目标对象中。因此,您需要迭代源对象的键而不是目标对象的键:附注:您可以编写
x == null
而不是x === null || x === 未定义
。节省一些宝贵的击键次数。The idea in
_.defaults
is that keys from the source object might be missing entirely in the destination object. So you need to iterate the keys of the source object instead of those of the destination object:Side note: you can write
x == null
instead ofx === null || x === undefined
. Saves some precious keystrokes.