简体   繁体   English

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

[英]Removing an object's array elements using splice()

Below I have defined an object and then created a 3x3 array with each element holding an instance of myObject.下面我定义了一个对象,然后创建了一个 3x3 数组,其中每个元素都包含一个 myObject 的实例。 I'm expecting function removeNumberFromArray to iterate over each element and therefore each object and remove the number 32 from the array called myNumbers.我期待函数 removeNumberFromArray迭代每个元素,因此每个对象并从名为 myNumbers 的数组中删除数字 32。 My comments indicate what it actually logs to the console.我的评论表明它实际记录到控制台的内容。 The result is an empty array and I was expecting to have each object within the 9x9 array to have myNumbers array equal to [7,51,2,0,9].结果是一个空数组,我希望 9x9 数组中的每个对象都使 myNumbers 数组等于 [7,51,2,0,9]。

I can't see where I am going wrong and I have tried breaking the problem down into smaller steps but splice seems to work, any ideas?我看不出哪里出错了,我尝试将问题分解为更小的步骤,但 splice 似乎有效,有什么想法吗?

I'm using VS Code with Liveserver Extension with Firefox Browser.我将 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);   //[]

By using Object.create(myObject) you are using prototypal inheritance to create an object that inherits from myObject , which is not what you're looking for.通过使用Object.create(myObject)您正在使用原型继承来创建一个从myObject继承的对象,这不是您要查找的对象。 I suggest you to create a small "factory" function to generate unique objects like this:我建议你创建一个小的“工厂”函数来生成这样的独特对象:

 const arrayLike = { length: 3 }; const myArray = Array.from(arrayLike, () => Array.from(arrayLike)); const objectFactory = () => ({ 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] = objectFactory(); } } function removeNumberFromArray(numberToRemove) { myArray.forEach(ele => { ele.forEach(square => { let index = square.myNumbers.indexOf(numberToRemove); if(~index) 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); //[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM