FreeCodeCampChina / freecodecamp.cn

FCC China open source codebase and curriculum. Learn to code and help nonprofits.

Home Page:https://fcc.asia/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

请教大神,为什么用多维数组不可以了???

pkbill511 opened this issue · comments

Challenge Filter Arrays with filter has an issue.
User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.
Please describe how to reproduce this issue, and include links to screenshots if possible.

My code:

var oldArray = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7]];

// 只能在这一行下面写代码

var newArray = oldArray.filter(function(arrOne,arrTwo){
  
  var newArrOne=arrOne.filter(function(val){
    return val<6;
    
  });
 var newArrTwo=arrTwo.filter(function(val){
    return val<6;
    
  });
  return [newArrOne,newArrTwo];
});

新手请教大神,多维数组用.filter为什么运行不了???

是.filter不适用多维数组???

还是我的代码有问题呢???

@pkbill511
注意看左边的报错:
image

以及文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
image

第一个参数是每个元素(也就是里面的子数组),第二个是 index(也就是 0 和 1),你对这个调用 filter 显然不行

filter 显然是适用于多维数组的,但你得想明白,你现在不是需要 filter 那个 oldArray(或者说你需要的不是改变 oldArray 的长度),而是要 filter oldArray 里面的每个子数组。因此,最后的结果也应该是与 oldArray 长度相等的二维数组。所以,你需要的其实是对 oldArray 调用 map 方法,里面才需要调用 filter 方法

image