问题描述
我想知道是否有一种简单的方法可以在关键位置之后拼接出所有元素.
I am wondering if there is an easy way to splice out all elements after a key position.
array.splice(index,howmany,item1,.....,itemX)
文档说,指定要删除的元素数量的第二个元素是必填字段,是否需要做个警告?
The docs say the 2nd element that specifies the number of elements to be removed is a required field, is there a caveat to get this done?
P.S-不寻求正常的蛮力解决方案.
P.S - Not looking for the normal brute force solutions.
推荐答案
如果在关键位置之后是 all 个元素,请执行以下操作:
If it's all elements after a key position, you do this:
array.length = theKeyPosition;
例如:
var array = [
"one",
"two",
"three",
"four",
"five",
"six"
];
var theKeyPosition = 3;
array.length = theKeyPosition; // Remove all elements starting with "four"
如果您尚不知道关键位置,则在ES5环境中(可以进行填充),可以使用 filter
:
If you don't yet know the key position, in an ES5 environment (and this can be shimmed), you use filter
:
var array = [
"one",
"two",
"three",
"four",
"five",
"six"
];
var keep = true;
array = array.filter(function(entry) {
if (entry === "four") {
keep = false;
}
return keep;
});
使用字符串,但是您可以轻松地将 if(entry ==="four"){
更改为 if(entry.someProperty === someValue){
您的对象数组.
That's using strings, but you can easily change if (entry === "four") {
to if (entry.someProperty === someValue) {
for your array of objects.
这篇关于使用splice删除Javascript中对象数组中某个位置之后的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!