简体   繁体   English

从数据拼接数组

[英]splice array from data

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.我在控制台和数组中尝试了kode_pelayanan是。 This array get from input这个数组从输入中获取

kode_pelayanan array ["LB1", "LB2", "LHA01", "LHA02"]

but when i run function deleteKodePelayanan() and splice LB2 .但是当我运行函数deleteKodePelayanan()和 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.找到索引,然后使用 splice 将其删除。

Use indexOf to find the index first.首先使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM