Javascript 如果my string test函数的输入为空,则返回false

Javascript 如果my string test函数的输入为空,则返回false,javascript,string,algorithm,Javascript,String,Algorithm,我正在做一个习题集,以查找“x”和“o”的出现次数,不区分大小写,如果它们在字符串中出现的次数相同,则返回true,否则返回false。这个问题集有几个边缘案例,其中一些我已经解决了,但是这个边缘案例仍然存在 Empty string contains equal amount of x and o - Expected: true, instead got: false 代码如下: function XO(str) { //code here var res_x = str

我正在做一个习题集,以查找
“x”
“o”
的出现次数,不区分大小写,如果它们在字符串中出现的次数相同,则返回true,否则返回false。这个问题集有几个边缘案例,其中一些我已经解决了,但是这个边缘案例仍然存在

Empty string contains equal amount of x and o - Expected: true, instead got: false
代码如下:

function XO(str) {
    //code here

    var res_x = str.match(/x/gi)
    var res_o = str.match(/o/gi)
    if (res_o !== null && res_x !== null) 
    {
      res = (res_o.length) == (res_x.length)?true:false

    } else if (res_o == "" || res_x == "") {

      res = true

    } else if (res_o == "" && res_x == "") {

      res = true

    } else if (res_o == null && res_x == null) {
        res = false
    } else {

      res = false

    }



    return res

}

这里的逻辑过于复杂。过多的分支和布尔使程序难以理解。边缘情况几乎是虚构的——空字符串不需要较长字符串的任何特殊逻辑

这里有一种可能的方法:从字符串中删除所有
“x”
字符,并计算长度。从字符串中删除所有
“o”
字符,并获取长度。如果删除后的长度相同,则返回true。将处理空字符串,因为
“”.length===“”.length

constxo=s=>s.replace(/x/gi,”).length==s.replace(/o/gi,”).length;
[
"",
“xo”,
“oxox”,
“xxoo”,
“xoo”,
“oxx”,
“x”,
“o”,
“oxxox”

].forEach(e=>console.log(xo(e))谢谢@ggorlen