使用 splice() 删除对象的数组元素

下面我定义了一个对象,然后创建了一个 3x3 数组,其中每个元素保存一个 myObject 实例。我期望函数removeNumberFromArray迭代每个元素以及每个对象,并从名为myNumbers 的数组中删除数字32。我的评论指出了它实际记录到控制台的内容。结果是一个空数组,我希望 9x9 数组中的每个对象的 myNumbers 数组等于 [7,51,2,0,9]。


我看不出哪里出了问题,我尝试将问题分解为更小的步骤,但拼接似乎有效,有什么想法吗?


我正在将 VS Code 与 Liveserver Extension 和 Firefox 浏览器结合使用。


const myObject = {

    myNumbers: [7,32,51,2,0,9],

    myName: "John",

    myLastName: undefined,

    age: 26

};


for (i = 0; i <= 2; i++) {

    for (j = 0; j <= 2; j++) {

        myArray[i][j] = Object.create(myObject);

    }

}


function removeNumberFromArray(numberToRemove) {

    myArray.forEach(ele => {

        ele.forEach(square => {

            let index = square.myNumbers.indexOf(numberToRemove);

            square.myNumbers.splice(index, 1);

        })

    });

}


console.log(myArray[0][0].myNumbers); //[7, 32, 51, 2, 0, 9]

removeNumberFromArray(32);

console.log(myArray[0][0].myNumbers);   //[]


慕容708150
浏览 179回答 2
2回答

米脂

通过使用,Object.create(myObject)您正在使用原型继承来创建一个继承自 的对象myObject,这不是您想要的。我建议您创建一个小型“工厂”函数来生成像这样的独特对象:

小唯快跑啊

const arrayLike = { length: 3 };const myArray = Array.from(arrayLike, () => Array.from(arrayLike));const objectFactory = () => ({&nbsp; &nbsp; myNumbers: [7, 32, 51, 2, 0, 9],&nbsp; &nbsp; myName: "John",&nbsp; &nbsp; myLastName: undefined,&nbsp; &nbsp; age: 26});for (i = 0; i <= 2; i++) {&nbsp; &nbsp; for (j = 0; j <= 2; j++) {&nbsp; &nbsp; &nbsp; &nbsp; myArray[i][j] = objectFactory();&nbsp; &nbsp; }}function removeNumberFromArray(numberToRemove) {&nbsp; &nbsp; myArray.forEach(ele => {&nbsp; &nbsp; &nbsp; &nbsp; ele.forEach(square => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let index = square.myNumbers.indexOf(numberToRemove);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(~index) square.myNumbers.splice(index, 1);&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; });}console.log(myArray[0][0].myNumbers); //[7, 32, 51, 2, 0, 9]removeNumberFromArray(32);console.log(myArray[0][0].myNumbers);&nbsp; &nbsp;//[]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript