我编写了一个接受 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/