除了使用 destructuring
以外,另一种选择是使用 delete
。以下方案将时间复杂性相比于 destructuring
减少约 35% (在桌面版 Chrome 中)。
解决方案
let obj = {foo: 1, bar: 2, baz: 3}
function removeProperty(obj, propertyName) {
let newObj = {...obj};
delete newObj[propertyName];
return newObj;
}
console.log(removeProperty(obj, 'foo'));
性能测试
https://jsperf.com/so53753276
结果因所用浏览器而异。结果相当引人入胜。桌面版Safari的解构
优于删除
,但桌面版Chrome比桌面版Safari所有数字都表现更好。
+
| Browser | delete | destructure |
+
| Chrome | 3,229,791 | 1,993,256 |
| Safari | 1,186,679 | 1,872,396 |
+
iOS上的结果并不令人意外,因为Chrome实际上就是在Safari引擎下运行。
+
| Browser | delete | destructure |
+
| Chrome | 1,146,496 | 1,785,551 |
| Safari | 1,182,067 | 1,793,772 |
+
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
delete
,或者过滤掉键:Object.keys(obj).filter(key => !forbiddenKeys.includes(key)).reduce((acc, key) => ({ ...acc, [key]: obj[key] }), {})
,但这看起来非常难看。最好还是采用前一种方法更清晰明了。 - Andrew Li