我正在做一项作业,必须接受一个 10 个单词的字符串并决定它属于哪个类别。该字符串可以是任何内容,并且必须由 3 个类别定义: 1. 猫。 A - 字符串主体,其中一半以上的单词不超过 4 个字符 2. 猫。 B - 字符串主体既不是 Cat。 A 或猫。 C 3. 猫。 C - 字符串主体,其中一半以上的单词为 7 个或更多字符
我遇到的问题是不知道使用哪些变量和运算符来开始剖析原始字符串。如果有人可以给出我应该执行的步骤列表,我将能够完成它。
这是我迄今为止的工作:
var sentence = "The quick brown fox jumps over the lazy dogs tomorrow";
var sentenceSplit = sentence.split(" ");
sentenceSplit[0];
sentenceSplit[1];
sentenceSplit[2];
sentenceSplit[3];
sentenceSplit[4];
sentenceSplit[5];
sentenceSplit[6];
sentenceSplit[7];
sentenceSplit[8];
sentenceSplit[9];
if (sentenceSplit[0].length <= 4 || sentenceSplit[1].length <= 4 || sentenceSplit[2].length <= 4 || sentenceSplit[3].length <= 4 || sentenceSplit[4].length <= 4
|| sentenceSplit[5].length <= 4 || sentenceSplit[6].length <= 4 || sentenceSplit[7].length <= 4 || sentenceSplit[8].length <= 4 || sentenceSplit[9].length <= 4) {
print ("good");
}else{
print ("bad");
}
最佳答案
在这类问题中,最好使用 for 循环,而不是凌乱的 if 语句,它很容易实现,如下所示:
let catAindicator = 0;
let catBindicator = 0;
let catCindicator = 0;
for (let item of sentenceSplit) {
if (item.length <= 4) {
console.log(item + " is Cat A");
catAindicator++;
} else if (item.length >= 7) {
console.log(item + " is Cat C");
catCindicator++;
} else {
console.log(item + " is Cat B");
catBindicator++;
}
}
console.log(catAindicator); //count of cat A words
console.log(catCindicator); //count of cat C words
console.log(catBindicator); //count of cat B words
现在,您可以使用指示类别字符串计数的三个变量,通过其子字符串的大多数类别来简单地评估字符串类别,例如catAindicator
在第一个条件下增加,如 catAindicator++
等等,然后比较它们,就得到结果。它会是这样的:
if (catAindicator > catBindicator && catAindicator > catCindicator){
console.log("String is Cat A");
} else if (catCindicator > catAindicator && catCindicator > catBindicator){
console.log("String is Cat C");
} else {
console.log("String is Cat B");
}
关于javascript - 我在 javascript 中使用算术运算符时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58868179/