javascript - 我在 javascript 中使用算术运算符时遇到问题
问题描述
我正在做一项作业,必须拿一个 10 字的字符串并决定它属于哪个类别。字符串可以是任何东西,它必须由 3 个类别定义: 1. Cat。A - 字符串的正文,其中一半以上的单词为 4 个字符或更少 2. Cat。B - 弦体既不是猫。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");
}
推荐阅读
- html - 具有背景渐变和填充的内联文本
- python - numpy 如果 A > 值,将 B 更改为常量
- git - 使用 git push 时遇到错误
- nlp - 如何(几乎)正确地检测到两个句子在语义上非常相似?
- java - a[ a[ i ] ] 在 Java 中做了什么?
- kubernetes - 使用 mountPath 时不允许 Rancher 操作
- c++ - 反转图,同时保持对按源或目标顶点排序的边的访问
- css - 如何让我的菜单下拉方向在视口边缘改变?
- kubernetes - Kubernetes HPA 自定义扩展规则
- vb.net - 如何从 VB.NET 调用后期绑定程序集。[名称]。方法?