[英]Unshift from object list without using delete?
如果可以使用list[value][index]
从对象访问对象,如何在不使用delete
情况下从list
删除或取消移动该对象? (因为这在对象列表中是不可能的)
我的对象看起来像这样:
var list = {
'test1': [
{
example1: 'hello1'
},
{
example2: 'world1'
}
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
删除对象后,我希望它看起来像这样:
var list = {
'test1': [
{
example1: 'hello1'
}
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
当我使用delete时,它看起来像这样:
var list = {
'test1': [
{
example1: 'hello1'
},
null
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
您可以通过将list[key]
的值设置为undefined
来从list
删除对象。 但是,这不会删除密钥-您需要delete
该密钥:
list['test1'] = undefined; // list is now { test1: undefined, test2: [ ... ]}
delete list['test1']; // list is now { test2: [ ... ] }
您是否有特定原因不想使用delete
? 它不会有所作为,如果你只是检查list['test1']
为感实性(例如, if (list['test1']) ...
),但如果你想通过遍历list
使用for (var key in list)
或类似的方法, delete
是一个更好的选择。
编辑:好的,看来您的实际问题是“如何从数组中删除值?”,因为这就是您正在做的事情-数组位于对象内,或者包含对象而不是其他值,是无关紧要的。 为此,请使用splice()方法:
list.test1.splice(1,1); // list.test1 has been modified in-place
(针对更正的问题进行了重写。)
你可以写:
list[value].splice(index, 1);
删除list[value][index]
,从而将数组缩短1。 (上述“替换” 1
元素,从position index
开始,不包含任何元素;有关该方法的常规文档,请参见MDN中的splice
。)
这是使用拼接的示例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.