1

我希望能够从数组中删除一个对象,而无需循环所有对象数组以查看当前数组元素是否具有我要删除的项目的 ID。

javascript:

function CBooks() {
    this.BooksArray = [];

    this.AddBook = function(divID, sContents) {
        this.BooksArray.push(new CBook());
        pos = this.BooksArray.length - 1;
        this.BooksArray[pos].ArrayID = pos;
        this.BooksArray[pos].DivID = divID;
        this.BooksArray[pos].Contents = sContents;
    }

    this.DelBook = function(divID) {
        this.BooksArray.splice(...);
    }
}

function CBook() {
    this.ArrayID = 0;
    this.DivID = "";
    this.Contents = "";
}

我像这样初始化对象:

var oBooks = new CBooks();

我添加了一本这样的新书:

oBooks.AddBook("divBook1", "blahblahblah");
//Creation of the div here
oBooks.AddBook("divBook2", "blehblehbleh");
//Creation of the div here

现在用户可以单击显示每本书的 div 中的 X 按钮,以便他可以删除该书。所以 X 按钮包含:

onclick=oBooks.DelBook(this.id);

现在显然在DelBook(divID)函数中,我可以遍历BooksArray的长度并查看每个元素是否 divID 等于参数并在该点拼接,但我想避免循环。

有什么办法吗?

提前致谢

4

3 回答 3

5

这样的事情会起作用,但前提是您愿意放弃用于哈希的数组。

您的代码已编辑

function CBooks() {
  this.BooksHash = {};

  this.AddBook = function(divID, sContents) {
    var book = new CBook();
    //book.ArrayID = pos; //you don't actually need this anymore using a hash
    book.DivID = divID;
    book.Contents = sContents;
    this.BooksHash[book.DivID] = book;
  }

  this.DelBook = function(divID) {
    delete this.BooksHash[divID];
  }
}

function CBook() {
  //this.ArrayID = 0; // same here
  this.DivID = "";
  this.Contents = "";
}

希望能帮助到你

于 2013-05-21T21:13:43.163 回答
2
arr.filter(function(item){
  Return item.id != idtoremove
 });

这将在幕后循环,但使用快速的本机代码并且更易于阅读。如果你真的想要 O(1) 删除,你需要使用某种哈希,并且会在创建和更新数组时增加额外的开销

于 2013-05-21T21:24:03.387 回答
0

我是这样解决的:

function CBooks() {
    this.BooksArray = [];
    this.Hashes = {};

    this.AddBook = function(divID, sContents) {
        this.BooksArray.push(new CBook());
        pos = this.BooksArray.length - 1;
        this.BooksArray[pos].ArrayID = pos;
        this.Hashes[divID] = pos;
        this.BooksArray[pos].DivID = divID;
        this.BooksArray[pos].Contents = sContents;
    }

    this.DelBook = function(divID) {
        this.BooksArray.splice(this.Hashes[divID], 1);
    }
}

function CBook() {
    this.ArrayID = 0;
    this.DivID = "";
    this.Contents = "";
}
于 2013-05-21T21:28:41.890 回答