删除数组中的一个对象,而不循环所有数组
delete an object of an array without looping all the array
我希望能够从数组中删除一个对象,而无需循环所有对象数组来查看当前数组元素是否具有我要删除的项的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是否等于该参数,然后在该点进行拼接,但我希望避免循环。
有什么办法吗?
提前感谢
这样的方法是可行的,但前提是您愿意放弃用于哈希的数组。
您的代码已编辑
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 = "";
}
希望它能帮助
arr.filter(function(item){
Return item.id != idtoremove
});
这将在封面下循环,但使用快速的本地代码,更容易阅读。如果你真的想删除O(1(,你需要使用某种散列,并在创建和更新数组时增加额外的开销
我这样解决了它:
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 = "";
}
相关文章:
- javascript:数组循环
- 如何将数组循环到JSON代码中
- 而与数组循环
- JavaScript 数组/循环不起作用
- AJAX在数组循环中调用,只在上一次完成后调用next
- 数组循环以获取单个值
- JavaScript数组循环
- Javascript 2D数组循环停止
- 通过Javascript中的JSON数组循环
- 为什么以下 forEach 数组循环未返回未定义
- 如何在数组循环中过滤数据
- 如何在数组循环 222 中过滤数据
- 数组循环以确定范围平均值
- 对象的数组循环
- 对象键及其值的数组循环
- 虽然的缺点!未定义的数组循环
- 数组循环导致无限循环
- 数组循环 - 处理下拉列表中的空值
- 在 Node 中连接数组循环.js glob 结果
- JavaScript 图像数组循环