javascript过滤具有复杂条件的荣誉

时间:2018-05-30 12:52:41

标签: javascript filter

为什么这样做:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(
  word => word.length > 6
);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

但在修改这篇文章之后,并没有:

const result = words.filter(
      word => {
        word.length > 6
      }
    );

请注意,我想将word.length > 6放在我想要实际拥有更复杂的中间计算(超过1行)的荣誉中。

任何建议,谢谢。

2 个答案:

答案 0 :(得分:0)

当表达式用括号括起来时,您需要使用return关键字:

const result = words.filter(
  word => {
    return word.length > 6
  }
);

答案 1 :(得分:0)

第一版:



var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    const result = words.filter(word => word.length > 6);
    console.log(result)




第二版



    var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
        const result = words.filter(word => {return word.length > 6});
        console.log(result)




当您使用第二个版本时,如果您有更复杂的条件

,则使用第一个版本