出于某种未知的原因,我无法让对象传播在我的代码中工作。我不得不依靠“Object.assign()”,但宁愿使用“...”
以下作品:
const frederick = {
name: 'Frederick Douglass',
canRead: false,
canWrite: false
};
// create new object and mutate that one
const selfEducate = person =>
Object.assign({}, person,
{canRead:true},
{canWrite:true}
);
console.log(selfEducate(frederick)); // { name: 'Frederick Douglass', canRead: true, canWrite: true }
console.log(frederick); // { name: 'Frederick Douglass', canRead: false, canWrite: false }
但是,以下情况则不然:
const frederick = {
name: 'Frederick Douglass',
canRead: false,
canWrite: false
};
const selfEducate = person =>
({
...person,
canRead: true,
canWrite: true
});
console.log(selfEducate(frederick));
console.log(frederick);
那个错误是:
SyntaxError: Unexpected token ...
扩展运算符确实可以在我的其他涉及复制数组的代码中工作,但在本示例中不行。如有任何反馈,我们将不胜感激。
最佳答案
如果代码的其他部分正在对数组使用展开运算符,那么这与尝试展开对象文字不同。
有建议让规范拥有它,例如 here .
关于javascript - JavaScript ES6 中的纯函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43928285/