开发者社区> 问答> 正文

使用JavaScript从数组中删除对象

如何从数组中删除对象?我想删除,其中包括名称的对象Kristian从someArray。例如:

someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];

我要实现:

someArray = [{name:"John", lines:"1,19,26,96"}];

展开
收起
保持可爱mmm 2020-01-13 18:46:56 483 0
1 条回答
写回答
取消 提交回答
  • 您可以使用多种方法从数组中删除项目:

    //1 someArray.shift(); // first element removed //2 someArray = someArray.slice(1); // first element removed //3 someArray.splice(0, 1); // first element removed //4 someArray.pop(); // last element removed //5 someArray = someArray.slice(0, a.length - 1); // last element removed //6 someArray.length = someArray.length - 1; // last element removed

    如果要删除position处的元素x,请使用:

    someArray.splice(x, 1);

    要么

    someArray = someArray.slice(0, x).concat(someArray.slice(-x));

    回复@ chill182的评论:您可以使用Array.filter或Array.splice结合使用Array.findIndex(参见MDN)从数组中删除一个或多个元素,例如

    // non destructive filter > noJohn = John removed, but someArray will not change let 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});

    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"} ]; }

    **Results**
    
    

    问题来源于stack overflow

    2020-01-13 18:47:47
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript面向对象的程序设计 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载