另一种选择destructuring
是使用delete
. destructuring
与(在桌面 Chrome 中)相比,以下解决方案将时间复杂度降低了约 35%
解决方案
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
结果因使用的浏览器而异。结果相当有趣。Desktop Safari的destructuring
表现优于delete
,但 Desktop Chrome 的表现优于 Desktop 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 |
+---------+-----------+-------------+
文档
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete