数组的元素不通过测试

时间:2016-09-13 20:14:06

标签: javascript arrays

我正在编写一个循环遍历数组的函数,并测试每个元素的条件。如果为false,则删除该元素。如果为true,则该函数返回数组的其余部分。

这是我的代码:

def getXML(): NodeBuffer = {
  <elem1>hello</elem1>
  <elem2>Sample text</elem2>
}

val test = getXML()
scala.xml.XML.save("test2.xml", test, "UTF-8", false, null) // Does not works

当循环达到i = 1时,我们有arr [1] = 2。

由于2不是&gt; = 3,我不明白它为什么不被删除。

那么,为什么以下调用

function dropElements(arr, func) {
    // Loop through the array
    for(var i = 0; i < arr.length; i++){
      // if the current element passes the test, return the rest of the array
      if (func(arr[i])){
        return arr;
      // otherwise remove the element
      } else {
        arr.shift();  
      }
    }
    // if no conditions were met, return empty array
    return arr;
}

返回[2,3,4]而不是[3,4]?

感谢。

4 个答案:

答案 0 :(得分:7)

因为当你“移动”它会移除索引而其他索引向下移动以填充孔。因此,当您删除第一个索引时,第二个索引现在是一个索引。由于您增加了i,因此您跳过了向下移动的索引。

因此,要解决您的问题,您需要减少i

else {
    arr.shift();
    i--;
}

或者你可以做另一个找到索引的解决方案,而不仅仅是拼接数组。

答案 1 :(得分:0)

来自MDN doc:

  

shift()方法从数组中删除第一个元素并返回该元素。此方法更改数组的长度。

在您的代码中,这意味着您必须在循环中同步索引。您可以简单地将索引减少1

function dropElements(arr, func) {
// Loop through the array
for(var i = 0; i < arr.length; i++){
  // if the current element passes the test, return the rest of the array
  if (func(arr[i])){
    return arr;
  // otherwise remove the element
  } else {
    arr.shift();i--;
  }
}
// if no conditions were met, return empty array
return arr;}

这将解决您的问题

答案 2 :(得分:0)

它与您移动数组的顺序有关。比较以下内容:

function dropElements(arr, func) {
    if (!Array.isArray(arr) && arr.length == 0) {
        return [];
    }

    while (!func(arr[0]) && arr.length > 0) {
        arr.shift();
    }

    return arr;
}

答案 3 :(得分:-1)

epascarello的答案应该被接受为正确的答案,但是这里是您需要的更新代码块:

function dropElements(arr, func) {
    // Loop through the array
    for(var i = 0; i < arr.length; i++){
      // if the current element passes the test, remove it from the array
      if (func(arr[i])){
        return arr;
      } else {
        arr.shift();
        i--;
      }
    }
    // Return the array
    return arr;
}

var arr = [1,2,3,4,2];
dropElements(arr, function(num) {
    return num >= 3;
});

这输出[3, 4, 2](这是因为我们假设当我们遍历它时数组是有序的,并且当测试函数满足一次时从函数返回)。如果你想循环一个无序数组,只需删除循环中的return arr,只需注意这将在O(n)处运行,而不是O(log n)