下划线“默认”从头开始

发布于 2025-01-15 21:22:14 字数 548 浏览 4 评论 0原文

我一直在尝试从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何时共饮酒 2025-01-22 21:22:14

_.defaults 中的想法是源对象中的键可能会丢失完全在目标对象中。因此,您需要迭代源对象的键而不是目标对象的键:

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};

附注:您可以编写 x == null 而不是 x === null || x === 未定义。节省一些宝贵的击键次数。

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] == null) {
      destination[key] = source[key];
    }
  })
  return destination;

};

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:

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};

Side note: you can write x == null instead of x === null || x === undefined. Saves some precious keystrokes.

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] == null) {
      destination[key] = source[key];
    }
  })
  return destination;

};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文