需要 .filter() 方面的帮助

时间:2021-06-28 13:29:44

标签: javascript

为什么当我在过滤器参数中添加花括号时,它不起作用?

// Write your code here:

function justCoolStuff(arr1,arr2){

  var newArray = arr1.filter(word => {arr2.includes(word)});
  return newArray

}






const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway']; 

console.log(justCoolStuff(myStuff, coolStuff))

然而,当我删除大括号时,代码将运行。我以为是函数?这应该是正确的语法还是我弄错了?

// Write your code here:

function justCoolStuff(arr1,arr2){

  var newArray = arr1.filter((word) => arr2.includes(word));
  return newArray

}






const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway']; 

console.log(justCoolStuff(myStuff, coolStuff))

5 个答案:

答案 0 :(得分:0)

你需要return语句 { return arr2.includes(word)}

答案 1 :(得分:0)

添加大括号时,隐式 return 不再起作用。您需要手动返回,即:

var newArray = arr1.filter(word => { return arr2.includes(word) });

请参阅basic syntax of arrow functions

答案 2 :(得分:0)

如果您采用不同的格式,它可能会帮助您理解 - var newArray = arr1.filter(word => {arr2.includes(word)});

var newArray = arr1.filter(word => {
  arr2.includes(word)
});

如果你这样看,你就错过了 return 语句。使用括号,return 语句是隐含的。

答案 3 :(得分:0)

箭头后面的大括号表示要执行的函数代码块。因此,在第一个示例中,您没有返回任何内容,因为您应该使用 return 关键字明确说明。但是,在第二个示例中,使用该语法时,可以理解您正在返回该布尔值,这正是过滤器方法所期望的。

答案 4 :(得分:0)

因为那些被视为函数的开始,然后您隐式需要返回。

但这里有一些关于如何在不返回的情况下使用大括号的见解。

// Write your code here:

function justCoolStuff(arr1,arr2) {
    var newArray = arr1.filter(word => {
        return arr2.includes(word);
    });
    return newArray;
}

const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway']; 

console.log(justCoolStuff(myStuff, coolStuff))

注意:

function doSomehting() {
  return 1;
}

// is equal to
const doSomething = () => 1;

// also equal to
const doSomething = () => {
  return 1;
}

// but not equal to
const doSomething = () => {
  1
}