所以我今天才发现这样做:
a = { b: { c: 1, d: 2 }, d: {} }
sub = a.b
// sub is { c: 1, d: 2 }
sub
现在实际上是存储在 a 中的对象,而不是克隆。
现在如果我这样做:
sub.c = "x"
// a is now: { b: { c: 'x', d: 2 }, d: {} } // nice
同样的事情也适用于数组。
所以我有这个数组:
arr = [{a: 1, b: 2}, {c: 3, d: 4}]
sub = arr[1]
我想从数组中删除 sub
以便 arr
变成:[{a: 1, b: 2}]
但是如果我执行 sub = null
,我只是将一个新值分配给 sub
。 delete
也是一样。
delete sub // will unset the sub variable, not the object that it references.
所以问题是:如何使用 sub
{c: 3, d: 4}
即使它有效,我也不能使用 delete arr[1]
因为我不知道索引。我正在使用 lodash
min
函数存储对象
最佳答案
要从数组中删除元素,无论是原始值还是对象,您仍然使用 splice
.要查找元素索引,您可以使用 indexOf
.可能是因为:
indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
如此组合在一起
arr.splice(arr.indexOf(sub), 1);
看看这个演示:
var arr = [{a: 1, b: 2}, {c: 3, d: 4}]
var sub = arr[1];
alert('Before: ' + JSON.stringify(arr));
arr.splice(arr.indexOf(sub), 1);
alert('After: ' + JSON.stringify(arr));
关于javascript - 将存储在变量中的对象的值设置为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26280154/