您可以使用多种方法从数组中删除项目:
//1someArray.shift(); // first element removed//2someArray = someArray.slice(1); // first element removed//3someArray.splice(0, 1); // first element removed//4someArray.pop(); // last element removed//5someArray = someArray.slice(0, a.length - 1); // last element removed//6someArray.length = someArray.length - 1; // last element removed
如果要删除position处的元素
x,请使用:
someArray.splice(x, 1);
要么
someArray = someArray.slice(0, x).concat(someArray.slice(-x));
您可以使用
Array.filter或
Array.splice结合使用
Array.findIndex参见MDN从数组中删除一个或多个元素,例如
// non destructive filter > noJohn = John removed, but someArray will not changelet someArray = getArray();let noJohn = someArray.filter( el => el.name !== "John" );log("non destructive filter > noJohn = ", format(noJohn));log(`**someArray.length ${someArray.length}`);// destructive filter/reassign John removed > someArray2 =let someArray2 = getArray();someArray2 = someArray2.filter( el => el.name !== "John" );log("", "destructive filter/reassign John removed > someArray2 =", format(someArray2));log(`**someArray2.length ${someArray2.length}`);// destructive splice /w findIndex Brian remains > someArray3 =let someArray3 = getArray();someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);log("", "destructive splice /w findIndex Brian remains > someArray3 =", format(someArray3));log(`**someArray3.length ${someArray3.length}`);// Note: if you're not sure about the contents of your array,// you should check the results of findIndex firstlet someArray4 = getArray();const indx = someArray4.findIndex(v => v.name === "Michael");someArray4.splice(indx, indx >= 0 ? 1 : 0);log("", "check findIndex result first > someArray4 (nothing is removed) > ", format(someArray4));log(`**someArray4.length (should still be 3) ${someArray4.length}`);function format(obj) { return JSON.stringify(obj, null, " ");}function log(...txt) { document.querySelector("pre").textContent += `${txt.join("n")}n`}function getArray() { return [ {name: "Kristian", lines: "2,5,10"},{name: "John", lines: "1,19,26,96"},{name: "Brian", lines: "3,9,62,36"} ];}<pre>**Results**</pre>


