freecodecamp 之:使用for循环遍历所有数组项

这里有一个函数 filteredArray

它接收一个arr数组和一个elem作为参数

并且返回一个新数组newArr

题目要求:
filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18) should return [ [10, 8, 3], [14, 6, 23] ]
filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2) should return [ ["flutes", 4] ]
filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter") should return [ ["amy", "beth", "sam"] ]
filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3) should return [ ]
The filteredArray function should utilize a for loop

就是遍历数组的子数组 [ [arr1], [arr2], [arr3] ],如果数组中的子数组里出现与elem相同的项(即子数组包含该项),则这个子数组返回[ ],没有重复就返回整个arrn并且添加到新数组newArr;

用indexOf 检索是否存在elem 不存在返回-1

function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
for(var i=0; i<arr.length ; i++){
  if(arr[i].indexOf(elem) === -1){
      newArr.push(arr[i]);
  }
}
  return newArr;
}

或者将数组arr先放入新数组再一个一个剔除,用splice确定剔除的目标 i 和个数;

function filteredArray(arr, elem) {
let newArr = [...arr];
// change code below this line
for( var i = 0 ; i<newArr.length; i++){
  for( var j=0;j<newArr[i].length;j++){
      if(newArr[i][j]===elem){
         newArr.splice(i,1);
         i--;
         break;
     }
  }
}
return newArr;
// change code above this line
}

猜你喜欢

转载自blog.csdn.net/qq_40642021/article/details/81171041