[英]splice array from data
我想拼接一個數組但索引不起作用
var kode_pelayanan = [];
function deleteKodePelayanan(index){
kode_pelayanan.splice(index, 1);
console.log(kode_pelayanan);
}
我在控制台和數組中嘗試了kode_pelayanan
是。 這個數組從輸入中獲取
kode_pelayanan array ["LB1", "LB2", "LHA01", "LHA02"]
但是當我運行函數deleteKodePelayanan()
和 splice LB2
。 價值是
["LB2", "LHA01", "LHA02"]
在拼接之前嘗試對索引進行一些驗證。
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);
}
如果我遵循思路,我認為您想知道如何根據不基於索引的元素值從數組中刪除元素。 答案是兩步。 找到索引,然后使用 splice 將其刪除。
首先使用indexOf
查找索引。
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"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.