js使用数组移位删除对象属性

时间:2021-07-31 02:24:06

I have an array and object in js:

我在js中有一个数组和对象:

var number = [23,234,654,3234];
var detail = {
              23:"John",
              234:"Doe",
              654:50,
              3234:"blue"
            };

Then using var remove = number.shift(), I can get the first value in the array (in this case, 23) and remove it from the array.

然后使用var remove = number.shift(),我可以得到数组中的第一个值(在本例中为23)并将其从数组中删除。

I am trying to remove the corresponding property from the object: In this case, it will be 23:"John".

我试图从对象中删除相应的属性:在这种情况下,它将是23:“约翰”。

I tried delete detail.remove; but no luck.

我试过删除detail.remove;但没有运气。

Any suggestions?

Thanks

2 个解决方案

#1


1  

According to MDN the delete operator is followed by an expression that should evaluate to a property reference. Your example delete detail.remove is in fact correct.

根据MDN,delete运算符后跟一个应该求值为属性引用的表达式。您的示例删除detail.remove实际上是正确的。

However, if you want to access a property programmatically (or numbered property, such as 23), use bracket notation.

但是,如果要以编程方式(或编号属性,如23)访问属性,请使用括号表示法。

// with variable
delete detail[remove];

// with string or integer
delete detail[23];

#2


1  

you can't use variable in obj.variable, the right way is obj[variable].

你不能在obj.variable中使用变量,正确的方法是obj [variable]。

So try this instead:

所以试试这个:

 delete detail[remove];

#1


1  

According to MDN the delete operator is followed by an expression that should evaluate to a property reference. Your example delete detail.remove is in fact correct.

根据MDN,delete运算符后跟一个应该求值为属性引用的表达式。您的示例删除detail.remove实际上是正确的。

However, if you want to access a property programmatically (or numbered property, such as 23), use bracket notation.

但是,如果要以编程方式(或编号属性,如23)访问属性,请使用括号表示法。

// with variable
delete detail[remove];

// with string or integer
delete detail[23];

#2


1  

you can't use variable in obj.variable, the right way is obj[variable].

你不能在obj.variable中使用变量,正确的方法是obj [variable]。

So try this instead:

所以试试这个:

 delete detail[remove];