How do i delete the 'test1' from db using the del function?
var db = [];
function add(input) {
for(var key in db) {
if(db[key][0]===input[0]) {
return;
}
}
db[db.length] = input;
}
function edit(input, upgrade) {
for(var key in db) {
if(db[key][0]===input) {
db[key] = upgrade;
}
}
}
function del(input) {
var index = db.indexOf(input);
if (index !== -1) {
db.splice(index, 1);
}
}
add(['test1', 'online']);
console.log(db);
edit('test1', ['test1','offline']);
console.log(db);
del('test1'); // FAILED still shows old values
console.log(db);
The actual problem is not with the splice
but with the indexOf
. It will return the index of the item, only if the item being searched is the same as the object in the array. So, you have to roll your own search function, like this
function del(input) {
var i;
for (i = 0; i < db.length; i += 1) {
if (db[i][0] === input) {
db.splice(i, 1);
return;
}
}
}
Note: Never iterate an array with for..in
. Use normal for
loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.