我不确定/\s/
是如何运作的。如果函数参数是空格(空格,制表符或返回),我只需要返回true
,否则返回false。
var ch = /\s/
var lett = A
function isWhiteSpace(lett) {
if (lett.test(ch)) {
return true
} else {
return false
}
}

答案 0 :(得分:2)
从你的代码:
var ch = /\s/ // you defining a Regex Object containing an expression var lett = "A" // there is the character or string to test ... further ... if (lett.test(ch)) { // here you'll get an error cause of inversed order of operands
javascript函数" test"是Regex内置对象的一部分 需要一个' regex'
类型的对象
*regexObj.test(str)*
或litterallymyRegex.test(myString)
有关更多信息,请阅读文档: Using Regex in javascript
因为/\s/
是一个正则表达式对象,你应该写:
ch.test(lett);
// or shortly
/\s/.test(lett);
// let's create a set (or dictionnary) of each characters you
// want to match like you have enumerated (space, tab or return)
// \s space
// \t tab
// \n return
// ^ if parameter begin by
// $ if parameter finish by
// you can understand that any desired char between ^ and $
// will verify you have only one char into the tested variable
var charsToMatch = /^[\s\t\n]$/
function isBlank(param)
{
if(charsToMatch.test(param))
return true;
else
return false;
}
// --> or more shortly
// you dont need to use if/else instructions because .test()
// is already returning the statement you want
function isBlank(param) { return charsToMatch.test(param); }
console.log(isBlank("\n")) // return true
console.log(isBlank("\n\n")) // return false, because too many chars
console.log(isBlank("\t")) // return true
console.log(isBlank("A")) // return false
console.log(isBlank(" ")) // return true
console.log(isBlank("")) // return false, because just empty
var charsToMatch = /^[\s\t\n]$/
它也可以这样写:
var charsToMatch = new RegExp("^[\s\t\n]$")
答案 1 :(得分:1)
您的代码中存在一些语法错误。它应该是这样的:
function isWhiteSpace(lett) {
return /\s/.test(lett);
}
var lett1 = ' ',
lett2 = '\n',
lett3 = 'A';
console.log(isWhiteSpace(lett1));
console.log(isWhiteSpace(lett2));
console.log(isWhiteSpace(lett3));