javascript - 将存储在变量中的对象的值设置为空

标签 javascript arrays

所以我今天才发现这样做:

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,我只是将一个新值分配给 subdelete 也是一样。

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/

相关文章:

javascript - Javascript 中基本原型(prototype)设计的问题

javascript - AngularJS:高度动态路由

javascript - 如何将值存储在 HashMap /数组中以便稍后进行比较

javascript - 防止javascript访问不存在的数组

arrays - 快速检查数组中的多个值与单个引用值,然后根据匹配值的索引执行操作

java - 如何从文件交替变量中读取值?

javascript - React Native 中的透明覆盖

javascript - 性能——用于提取单个值的 match() 与 exec()

javascript - 在 catch block nodejs/javascript 中有 promise 问题

javascript - 相当于 C# LINQ GroupBy 的 Typescript 是什么?