我已经编写了一个小函数,该函数接受x和o。如果字符串中每个字母的编号相同,则该函数返回true
我的问题是我试图通过此测试,code wars
并且测试返回:
TypeError:无法在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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句