清理三元语句中的代码[重复]

时间:2021-06-20 00:16:14

This question already has an answer here:

这个问题在这里已有答案:

I am trying to count all the times the letter x and the letter o appear in a string and I'm returning true if they appear the same number of times and false otherwise.

我试图计算字母x和字母o出现在字符串中的所有时间,如果它们出现相同的次数,我将返回true,否则返回false。

I've completed the problem, but when using a ternary statement it forced me to create an extra condition I didn't need since you seem to need 3 operations in a ternary statement so I just counted every time something else appears in a string. Is there any way I can use a ternary statement without creating an unnecessary condition or would I have to use if statements?

我已经完成了这个问题,但是当使用三元语句时,它迫使我创建一个我不需要的额外条件,因为你似乎需要在三元语句中进行3次操作,所以我只是计算每次在字符串中出现其他内容。有没有什么办法可以在不创建不必要条件的情况下使用三元语句,或者我是否必须使用if语句?

function ExOh(str) {
  var ex = 0
  var oh = 0
  var other = 0
  for (var i = 0; i < str.length; i++) {
    str[i] === "x" ? ex++ : str[i] === "o" ? oh++ : other++
  }
  return ex === oh
}

console.log(ExOh("xooabcx$%x73o"));
console.log(ExOh("xooxxo"));
console.log(ExOh("x"));
console.log(ExOh(""));

//wouldn't let me just have one statement after the ternary so I created the other variable.

1 个解决方案

#1


2  

Why not add the boolean value?

为什么不添加布尔值?

ex += str[i] === "x";
oh += str[i] === "o";

Example

var a = 0;
a += false;
document.write(a + '<br>');
a += true;
document.write(a + '<br>');

While you just need the difference, you can use a single variable and count up for x and down for o. The return value is the not value of count.

虽然您只需要差异,但您可以使用单个变量并计算x和向下计数o。返回值不是count的值。

function ExOh(str) {
    var count = 0, i;
    for (i = 0; i < str.length; i++) {
        count += str[i] === "x";
        count -= str[i] === "o";
    }
    return !count;
}

document.write(ExOh("xooabcx$%x73o") + '<br>');
document.write(ExOh("xooxxo") + '<br>');
document.write(ExOh("x") + '<br>');
document.write(ExOh("") + '<br>');

#1


2  

Why not add the boolean value?

为什么不添加布尔值?

ex += str[i] === "x";
oh += str[i] === "o";

Example

var a = 0;
a += false;
document.write(a + '<br>');
a += true;
document.write(a + '<br>');

While you just need the difference, you can use a single variable and count up for x and down for o. The return value is the not value of count.

虽然您只需要差异,但您可以使用单个变量并计算x和向下计数o。返回值不是count的值。

function ExOh(str) {
    var count = 0, i;
    for (i = 0; i < str.length; i++) {
        count += str[i] === "x";
        count -= str[i] === "o";
    }
    return !count;
}

document.write(ExOh("xooabcx$%x73o") + '<br>');
document.write(ExOh("xooxxo") + '<br>');
document.write(ExOh("x") + '<br>');
document.write(ExOh("") + '<br>');