方法应返回包含少于6个字符的所有字符串的数组,或以e开头

时间:2019-04-27 02:43:05

标签: javascript string methods numbers

写一个方法strange_words接受一个字符串数组 该方法应返回一个数组,其中包含所有少于6个字符或以“ e”开头的字符串。

    function strangeWords(words){
      //write your code here
     }
   function printStringArray(strings){
 if(strings.length===0){
   console.log('[]');
  }else{
   console.log(`[${strings.join(',')}]`);
   }
   }
 printStringArray(strangeWords(["taco","eggs","excellent","exponential","artistic","cat","eat"]))

3 个答案:

答案 0 :(得分:0)

使用filter返回满足条件的字符串

function printStringArray(strings){
  return strings.filter((str) => str.length <= 6 || str.startsWith('e'));
}

console.log(printStringArray(["taco","eggs","excellent","exponential","artistic","cat","eat"]));

答案 1 :(得分:0)

使用filter,并检查length是否小于6,或者字符串的第一个字符是e

function strangeWords(words) {
  return words.filter(w => w.length < 6 || w.toLowerCase()[0] == "e");
}

console.log(strangeWords(["taco", "eggs", "excellent", "exponential", "artistic", "cat", "eat"]));

答案 2 :(得分:0)

function strangeWords(words) {
  return words.filter(word => (word.length < 6 || word.search(/^[eE].*/)));
}

console.log(strangeWords(["taco", "eggs", "excellent", "exponential", "artistic", "cat", "eat"]));