删除数组元素(如果它不存在)

时间:2015-07-08 11:35:59

标签: javascript jquery javascript-events

如果元素不存在,我想从数组ids中删除一个元素。

<div id="nl-form-0" > 
  <input type="text" id='dynamic_translation_0_0' value="15" />
  <input type="text" id='dynamic_translation_0_1' value="15" />
  <input type="text" id='dynamic_translation_0_2' value="15" />
  <input type="text" id='dynamic_translation_1_2' value="15" />
</div> 

ids = [
  "transliterateTextarea",
  "dynamic_translation_0_0",
  "dynamic_translation_0_1",
  "dynamic_translation_0_2",
  "dynamic_translation_1_0",
  "dynamic_translation_1_1",
  "dynamic_translation_1_2"];

check_remove_ids_array(ids);
console.log(ids);
console.log($("#dynamic_translation_1_1").length);

function check_remove_ids_array(array_in) {
  array_length = array_in.length;

  for (n = 0; n <= array_length; n++) { 
    if ($("#" + array_in[n]).length == '0') {
        removeValue(ids,array_in[n]);
    }          
  }     
}

function removeValue(arr, value) {
  var array = arr;

  for (var i = array.length-1; i--;) {
    if (array[i] === value) {
      array.splice(i, 1);
    }
  }

  return array;
}

在上面的代码中dynamic_translation_1_1不存在。如果元素不存在,我想从数组ids中删除该元素或任何其他元素

1 个答案:

答案 0 :(得分:0)

为什么/它不起作用?

基本上你有一个返回和分配问题。由于JavaScript中没有引用参数,因此必须将返回的数组分配回初始ID。您的removeValue()函数也是如此。

建议

使用array.filter()原型代替。它更优雅地解决了你的问题。

实施例

<html>
    <head>
        <script src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>

        <script>
            $(document).ready(function(){
                ids = ["transliterateTextarea", "dynamic_translation_0_0", "dynamic_translation_0_1", "dynamic_translation_0_2", "dynamic_translation_1_0", "dynamic_translation_1_1", "dynamic_translation_1_2"];
                ids = check_remove_ids_array(ids); //We have to assign it back, else we always get the initial ids array!
                console.log(ids);
                console.log($("#dynamic_translation_1_1").length);
            });

            function check_remove_ids_array(array_in){
                array_length = array_in.length; //Is not required in this example anymore.

                //We use the filter function instead.
                return array_in.filter(function(item){return $("#" + item).length > 0})
            };
        </script>
    </head>

    <body>
        <input type = 'text' id = 'dynamic_translation_0_0' value = '15' />
        <input type = 'text' id = 'dynamic_translation_0_1' value = '15' />
        <input type = 'text' id = 'dynamic_translation_0_2' value = '15' />
        <input type = 'text' id = 'dynamic_translation_1_2' value = '15' />
    </body>
</html>