i want to splice an array but index doesn't work
var kode_pelayanan = [];
function deleteKodePelayanan(index){
kode_pelayanan.splice(index, 1);
console.log(kode_pelayanan);
}
i tried in console and array for kode_pelayanan
is. This array get from input
kode_pelayanan array ["LB1", "LB2", "LHA01", "LHA02"]
but when i run function deleteKodePelayanan()
and splice LB2
. the value is
["LB2", "LHA01", "LHA02"]
Try some validation on the index before splice.
function deleteKodePelayanan(index){
index = parseInt(index,10);
if (isNaN(index)) {
// index is not a number
return;
} else if (!(index in kode_pelayanan)) {
// index is a number but the value isn't set
return;
}
kode_pelayanan.splice(index, 1);
}
If I follow the train of thought I think you want to know how to remove an element from an array based on the values of the elements not based on the index. The answer is two steps. Find the index then use splice to remove it.
Use indexOf
to find the index first.
var kode_pelayanan = ["LB1", "LB2", "LHA01", "LHA02"];
function deleteKodePelayanan(value){
var index = kode_pelayanan.indexOf(value);
if (index >= 0) {
kode_pelayanan.splice(index, 1);
}
console.log(kode_pelayanan);
}
deleteKodePelayanan("LB2"); // => ["LB1", "LHA01", "LHA02"]
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.