javascript - 调用 .length 时无法读取 null 的属性 'length'

标签 javascript

  • 我编写了一个接受 x 和 o 的小函数。如果字符串中每个字母的数量相同,则函数返回 true

  • 我的问题是我试图让此测试在代码 war 中通过,并且测试正在返回:

    类型错误:无法在 XO 处读取 null 属性“长度”

为什么会出现这样的情况呢?我该如何解决这个问题?

    function XO(str) {
      x = str.match(/[x]/gi).length
      y = str.match(/[o]/gi).length



       return x == y ? true : false 
    }

最佳答案

您需要考虑传递给函数的备用值和空值 - 您也可以忽略返回中的三元方程,只返回比较运算符的结果。

console.log(XO('x')); // returns false since there is 1 'x' and 0 'o'
console.log(XO('o')); // returns false since there is 0 'x' and 1 'o'
console.log(XO('abc')); // returns true since there is 0 'x' and 0 'o'

function XO(str) {
 if(str) {
    x = str.match(/[x]/gi) || [];
    y = str.match(/[o]/gi) || [];
    return x.length == y.length;
  } else {
    return false;
  }
}

关于javascript - 调用 .length 时无法读取 null 的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47606770/

相关文章:

javascript - JS正则表达式的问题

javascript - 在匹配的 DOM 元素集上使用 jQuery 时,是否需要使用索引号?

javascript - 在javascript中读取具有不同时区的日期字符串

JavaScript postMessage 和多个可传输对象

javascript - 虚拟 "Back Button"jquery

javascript - .hover() 在 jQuery 中不起作用

javascript - 浮起来的行

javascript - 在 Ionic3 中订阅提供程序后,Console.log 显示为未定义

javascript - 有人可以解释一下 VS Code 中的所有格式化工具是如何工作的吗?

javascript - 我如何用我的数据库值显示图表