简体   繁体   English

选择使用javascript es5更新或推送到数组

[英]Choose to update or push to array using javascript es5

I am trying to push an object into an array of objects but only if the particular object is not present in the array. 我试图push一个对象push对象数组,但object是该数组中不存在特定object If it is present the object should be updated. 如果存在,则应更新对象。

I am required to do this with es5 我需要使用es5进行此操作

Below is what I have tried 以下是我尝试过的

var database = require('../../database');
var autoincrementId = require('../../helpers/autoincrement-id');
var books = database.Books;

function Book(title, author, summary) {
  this.title = title;
  this.author = author;
  this.summary = summary;
}

Book.prototype.createBook = function () {
  var id = autoincrementId(id, database.Books); //autoincrement database id
  var copies = 1;
  var title = this.title.toLowerCase(), author = 
this.author.toLowerCase(), summary = this.summary.toLowerCase();
  if (!books.length) {
    books.push({id: id, title: title, author: author, summary: summary, copies: copies});
  } else {
     for(var book in books) {
      if(books[book].title === title) {
        books[book].copies += 1;
       break;
      }
      books.push({id: id, title: title, author: author, summary: summary, copies: copies});
    }
  }
};

But when i run the following 但是当我运行以下命令时

var abook = new Book('J', 'k', 'l');
var bbook = new Book('M', 'N', 'o');
abook.createBook();
abook.createBook();
bbook.createBook();
bbook.createBook();

console.log(books);

I get the following 我得到以下

[ { id: 1, title: 'j', author: 'k', summary: 'l', copies: 2 },
  { id: 2, title: 'm', author: 'n', summary: 'o', copies: 2 },
  { id: 3, title: 'm', author: 'n', summary: 'o', copies: 1 } ]

Instead of 代替

[ { id: 1, title: 'j', author: 'k', summary: 'l', copies: 2 },
  { id: 2, title: 'm', author: 'n', summary: 'o', copies: 2 }]

Can someone please help me understand the problem with this code. 有人可以帮助我了解此代码的问题。 Why does it update and insert at the second time and how can i solve this? 为什么第二次更新并插入?我该如何解决?

In your for(var book in books) { loop, you are checking if the current book is equal to the new one, then, if it's not the case, you add it. for(var book in books) {循环中,您正在检查当前书是否与新书相等,然后,如果不是,则添加它。 if the book is actually the second one of the list, it will be added since the first book checked isn't the new one. 如果这本书实际上是列表中的第二本书,则会添加该书,因为选中的第一本书不是新书。 You might need a flag to ensure that no book was found : 您可能需要标记以确保未找到书:

var BookNotFound = true; // by default, no book found
for(var book in books) {
    if(books[book].title === title) {
        books[book].copies += 1;
        BookNotFound = false; // <------- a book was found
        break;
    }
}
// Outside of the loop :
if (BookNotFound)
    books.push({id: id, title: title, author: author, summary: summary, copies: copies});

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

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