[英]Unshift from object list without using delete?
If I can access an object from an object using list[value][index]
, how can I delete or unshift that object from list
without using delete
? 如果可以使用
list[value][index]
从对象访问对象,如何在不使用delete
情况下从list
删除或取消移动该对象? (since that isn't possible in an object list) (因为这在对象列表中是不可能的)
My object looks like this: 我的对象看起来像这样:
var list = {
'test1': [
{
example1: 'hello1'
},
{
example2: 'world1'
}
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
After deleting an object, I want it to look like this: 删除对象后,我希望它看起来像这样:
var list = {
'test1': [
{
example1: 'hello1'
}
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
When I use delete, it looks like this: 当我使用delete时,它看起来像这样:
var list = {
'test1': [
{
example1: 'hello1'
},
null
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
You can remove the object from list
by setting the value of list[key]
to undefined
. 您可以通过将
list[key]
的值设置为undefined
来从list
删除对象。 This won't remove the key, however - you'd need delete
to do that: 但是,这不会删除密钥-您需要
delete
该密钥:
list['test1'] = undefined; // list is now { test1: undefined, test2: [ ... ]}
delete list['test1']; // list is now { test2: [ ... ] }
Is there a particular reason you don't want to use delete
? 您是否有特定原因不想使用
delete
? It won't make a difference if you're just checking list['test1']
for truthiness (eg if (list['test1']) ...
), but if you want to iterate through list
using for (var key in list)
or something like that, delete
is a better option. 它不会有所作为,如果你只是检查
list['test1']
为感实性(例如, if (list['test1']) ...
),但如果你想通过遍历list
使用for (var key in list)
或类似的方法, delete
是一个更好的选择。
EDIT: Ok, it looks like your actual question is "How can I remove a value from an array?", since that's what you're doing - the fact that your array is within an object, or contains objects rather than other values, is irrelevant. 编辑:好的,看来您的实际问题是“如何从数组中删除值?”,因为这就是您正在做的事情-数组位于对象内,或者包含对象而不是其他值,是无关紧要的。 To do this, use the splice() method:
为此,请使用splice()方法:
list.test1.splice(1,1); // list.test1 has been modified in-place
(Rewritten for corrected question.) (针对更正的问题进行了重写。)
You can write: 你可以写:
list[value].splice(index, 1);
to delete list[value][index]
and thereby shorten the array by one. 删除
list[value][index]
,从而将数组缩短1。 (The above "replaces" 1
element, starting at position index
, with no elements; see splice
in MDN for general documentation on the method.) (上述“替换”
1
元素,从position index
开始,不包含任何元素;有关该方法的常规文档,请参见MDN中的splice
。)
Here is an example using splice: 这是使用拼接的示例:
http://jsfiddle.net/hellslam/SeW3d/ http://jsfiddle.net/hellslam/SeW3d/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.