Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我会得到;TypeError:input.match(…)为null;?_Javascript_Html_Error Handling - Fatal编程技术网

Javascript 为什么我会得到;TypeError:input.match(…)为null;?

Javascript 为什么我会得到;TypeError:input.match(…)为null;?,javascript,html,error-handling,Javascript,Html,Error Handling,我有一个输入框,我希望根据您键入的文本发出特定警报。当我键入除“hello”之外的内容时,我不断收到错误“TypeError:input.match(…)为null” 我的代码: <html> <body> <form name="form5"> <input type=text size=51 name="input"> <input onClick=auswert() type=button value="submit"&g

我有一个输入框,我希望根据您键入的文本发出特定警报。当我键入除“hello”之外的内容时,我不断收到错误“TypeError:input.match(…)为null”

我的代码:

<html>
<body>
<form name="form5">
   <input type=text  size=51 name="input">
   <input onClick=auswert() type=button value="submit">
</form>
<script type="text/javascript">

function auswert() {
var input = document.form5.input.value;

if (input.match(/hello/g).length == 1) alert("hello");
else alert("bye");
}

</script>
</body>
</html>

函数auswert(){
var输入=document.form5.input.value;
if(input.match(/hello/g).length==1)警报(“hello”);
其他警报(“再见”);
}

来自Mozilla开发者网络文档:

“包含整个匹配结果和任何括号的数组捕获匹配结果;如果没有匹配项,则为null。”

input.match(/hello/g)
返回null。然后在
null
上调用
length
null
没有可以对其调用的函数

我建议你试试:

if (input.match(/hello/g) == null) {
    // No Matches
    alert("bye");
} else {
    // Matches
    alert("hello");
}

来自Mozilla开发者网络文档:

“包含整个匹配结果和任何括号的数组捕获匹配结果;如果没有匹配项,则为null。”

input.match(/hello/g)
返回null。然后在
null
上调用
length
null
没有可以对其调用的函数

我建议你试试:

if (input.match(/hello/g) == null) {
    // No Matches
    alert("bye");
} else {
    // Matches
    alert("hello");
}

因为如果没有匹配项,
input.match(/hello/g)
返回
null
。阅读文档总是很有用的。如果不想阅读文档,可以编写更好的逻辑
if((input.match(/hello/g))&&(input.match(/hello/g).length==1))
.match()
的结果分配给一个变量要比执行两次匹配工作好得多,因为这可能需要大量CPU。或者,未经测试,
if((input.match(/hello/g)| |[]).length==1){…
,因为
input.match(/hello/g)
如果不匹配,则返回
null
。阅读文档总是很有用的。如果不想阅读文档,可以编写更好的逻辑
if((input.match(/hello/g))&&(input.match(/hello/g).length==1))
.match()
的结果分配给一个变量要比执行两次匹配工作好得多,因为这可能需要大量CPU。或者,未经测试,
if((input.match(/hello/g)| |[]).length==1){…