for 循环:javaScript 中的嵌套数组

for loop: Nested array in javaScript

我的代码:

let newArr = [[1,5,6,4],[8,5,4],[4,4,4,4]];

function filterArr(arr, elemn){
  for(let i = 0; i < arr.length; i++){
    for(let j=0; j < arr[i].length; j++){
        if(arr[i][j] === elemn){
        arr[i].splice(j,1);
      }
    }
  }
  return arr;
}

console.log(filterArr(newArr,4));

结果: [[1,5,6],[8,5],[4,4]]

我卡在这一点上了: [4,4] 它应该是 []

有什么建议请...

我会引用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

中的一些句子

deleteCount Optional
An integer indicating the number of elements in the array to remove from start.

If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted.

If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).

您删除第 j 个元素和 j++ 以便在删除后跳过下一个被删除的元素。删除后你应该使用 j--.

完整权限代码如下:

let newArr = [[1,5,6,4],[8,5,4],[4,4,4,4]];

function filterArr(arr, elemn){
  for(let i = 0; i < arr.length; i++){
    for(let j=0; j < arr[i].length; j++){
        if(arr[i][j] === elemn){
        arr[i].splice(j, 1);
        j --;
      }
    }
  }
  return arr;
}

console.log(filterArr(newArr,4));

全局新数组。

let newArr = [[1,5,6,4],[8,5,4],[4,4,4,4]];

这里是filterArr函数,参数相同

let result = [];
for (let item of newArr){
    for (let i = 0; i< item.length; i++){
        if (item[i] == elemn){
            item.splice(i, 1);
            i--;
        }
    }
     result.push(item);
}

return result;

您可以调用 filterArr 函数并显示与您预期相同的结果。

console.log(filterArr(newArr,4));

如评论中所述,您可以查看 javascript Array class。有一个内置的 filter 方法可以稍微简化这一点。

let newArr = [[1,5,6,4],[8,5,4],[4,4,4,4]];

function filterArray(arr, valueToFilter) {
   return arr.map( (subArray) => subArray.filter( (value) => value !== valueToFilter ) );
}

console.log(filterArray(newArr,4));