简体   繁体   English

如何在对象数组中添加、更新、删除和搜索 object

[英]how to add, update, delete and search object inside array of objects

Hello I have an empty array, then I push inside objects, but is not getting updated, it going back to empty again.你好,我有一个空数组,然后我推入对象,但没有得到更新,它又变回空了。 this on node.js.这在 node.js 上。 i need to get as the first argument - from the commend line one of three string that do something to the array: 'add' to add new item to the array, 'delete' for delete frm the array and and 'update' for update the array.我需要获取作为第一个参数 - 从命令行中对数组执行操作的三个字符串之一:'add' 将新项目添加到数组中,'delete' 用于删除数组,'update' 用于更新数组。 second argument is name of the book,third argument author, and last arugmnt pages.第二个参数是书名、第三个参数作者和最后一个参数页。

    let arrayOfBooks = [];

// Assign places to the array 
let whichArgument = process.argv[2]
let name = process.argv[3];
let author = process.argv[4];
let pages = Number(process.argv[5]);

// Function constructor
function Book(name,author,pages) {
    this.name = name;
    this.author = author;
    this.pages = pages;
}

// Add function
const addBook = (arrayOfBooks)=> {
    arrayOfBooks.push(new Book(name, author, pages));
    return arrayOfBooks
}
let result = addBook(arrayOfBooks);

Your method works, but maybe you are loosing the reference by using the same name to the array and the params.您的方法有效,但也许您通过对数组和参数使用相同的名称来丢失引用。 But anyway, as the method .push does not return an updated array, just it modifies the same array instance, you don't need to return the pushed array, just use it.但无论如何,由于.push方法不会返回更新后的数组,只是修改了相同的数组实例,因此不需要返回推送的数组,只需使用它即可。

const arrayOfBooks = [
    {book: 1},
  {book: 2},
  {book: 3},
  {book: 4},
]

const addBook = (list, book) => {
    list.push(book)
}

addBook(arrayOfBooks, {book: 5, isTheNewOne: true})

const result = arrayOfBooks
console.log(result)
// Array with 5 elements now

See in fiddle小提琴

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

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