“Object.assign() 不会抛出 null 或未定义的源值”是什么意思?

问题描述 投票:0回答:2

我在 mozilla

上读到了这篇文章

“Object.assign() 不会抛出 null 或未定义的源值”

当我尝试使用它时

jsbin
,似乎不起作用。

var obj1 = {p: null};
var obj2 = {p: "new"};

console.log(_.assign(obj1, obj2));
console.log(_.merge(obj1, obj2));
console.log(Object.assign(obj1, obj2));
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
</head>
<body>

</body>
</html>

谁能帮我解释一下为什么?谢谢回复~

javascript ecmascript-6
2个回答
4
投票

这只是意味着你可以写

console.log(Object.assign({}, null));

并且它不会抛出错误。而已。您提供的示例按预期工作。


0
投票

如果您想连接对象,但希望代码在出现 null 或未定义值时抛出错误,您可以使用展开运算符。

这会起作用:

const one = { foo: 'bar' };
const two = null;
const joined = Object.assign(one, two); // Returns { foo: 'bar' };

但这会抛出异常:

const one = { foo: 'bar' };
const two = null;
const joied = { ...one, ...two }; // Throws a TypeError
© www.soinside.com 2019 - 2024. All rights reserved.