每个单词中的字符数

时间:2017-12-21 12:37:54

标签: javascript for-loop split count

我想开发一个代码来计算句子中每个单词的字符数,并测试它是否在2到14个字符之间。

如果它在2到14个字符之间,那么result1 = true

否则result1 = false

这是我的代码:

var sentence = "Now is the time for all men"
var re = /\s+/;
var resultat1 = false;
var nameList = sentence.split(re); //cutting the sentence into words
console.log(nameList);               //List of words in the sentence
var NbMot = nameList.length; //Number of words in the sentence
var NbCarMot = 0; //Numer of caracter in each word
for (i = 0; i < NbMot; i++) {
  NbCarMot = (nameList[i].length); //Numer of caracter in each word
  console.log(NbCarMot);
}
console.log(NbCarMot);
if (NbCarMot <= 14) {
  resultat1 = true;
}
console.log(resultat1)

2 个答案:

答案 0 :(得分:2)

str(x(a(3,4), b(,b1 = 5)))
#List of 2
# $ x1:List of 2
#  ..$ x: num 3
#  ..$ y: num 4
# $ x2:List of 2
#  ..$ b1: symbol 
#  ..$ b2: num 5

答案 1 :(得分:0)

  

我想开发一个计算每个字符数的代码   单词在一个句子中并测试它是否在2到14个字符之间,

一旦发现第一次违反规则 (2到14个字符之间) ,您就需要摆脱循环。

使用some

尝试这个简单的方法
var isInvalid = sentence.split( /\s+/ ).some( s => s.length < 2 || s.length > 14 );
相关问题