我想知道是否有一种简单的方法,在关键位置后剪切所有元素。
array.splice(index,howmany,item1,.....,itemX)
文档指出,第二个元素是指定要删除的元素数量的必填字段,是否有什么要注意的地方?
附注 - 不要寻求通常的暴力解决方案。
array.splice(index,howmany,item1,.....,itemX)
文档指出,第二个元素是指定要删除的元素数量的必填字段,是否有什么要注意的地方?
附注 - 不要寻求通常的暴力解决方案。
array.length = theKeyPosition;
E.g.:
var array = [
"one",
"two",
"three",
"four",
"five",
"six"
];
var theKeyPosition = 3;
array.length = theKeyPosition; // Remove all elements starting with "four"
如果您还不知道关键位置,在ES5环境中(这可以模拟),您可以使用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) {
,用于处理对象数组。
const array = [
"one",
"two",
"three",
"four",
"five",
"six"
];
const theKeyPosition = 3;
array.splice(theKeyPosition+1); // Remove all elements starting with "four"
console.log(array);
然而,我仍然更喜欢设置长度属性,因为它应该更快(我找不到JSPerf结果,请在这里帮助我)。
var a = [1,2,3,4,5]; a.splice(2); console.log(a);
。 - dfsq.length
来实现此目的。另外,您拥有的是JavaScript数组。JSON是一种文本格式。 - jfriend00splice
,但同时又不想使用splice
,而且你不想要一个“蛮力解决方案”,无论那是什么,T.J.的解决方案肯定是最“蛮力”的,但它很可能正是你要找的? - adeneo"[1, 2, 3, 4]"
这就是一个JSON数组。;-D (我知道你知道,只是想逗你开心一下。) - T.J. Crowder