Javascript 检查参数是否传递给 Java Script 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11461428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if argument is passed to a Java Script function
提问by KAPILP
Call to a JS function
调用 JS 函数
alertStatement()
Function Definition
功能定义
function alertStatement(link) {
if (link) {
alert('A');
}
if (link!=null) {
alert('B');
}
}
Both of these statements are working fine in Windows Env with Tomcat, but none of them execute it on production (Linux server). Is there any other way to compare variables to make it working?
这两个语句在带有 Tomcat 的 Windows Env 中都可以正常工作,但它们都没有在生产(Linux 服务器)上执行它。有没有其他方法可以比较变量以使其工作?
I got it working using the following javascript code.
我使用以下 javascript 代码让它工作。
function alertStatement(link) {
if (link!==undefined){
alert('A');
}
}
So at last undefined worked for me , for some reason null comparison didn't work
所以最后 undefined 对我有用,由于某种原因空值比较不起作用
回答by jfriend00
To see if the argument has a usable value, just check if the argument is undefined. This serves two purposes. It checks not only if something was passed, but also if it has a usable value:
要查看参数是否具有可用值,只需检查参数是否未定义。这有两个目的。它不仅会检查是否传递了某些内容,还会检查它是否具有可用值:
function alertStatement(link) {
if (link !== undefined) {
// argument passed and not undefined
} else {
// argument not passed or undefined
}
}
Some people prefer to use typeof like this:
有些人喜欢像这样使用 typeof:
function alertStatement(link) {
if (typeof link !== "undefined") {
// argument passed and not undefined
} else {
// argument not passed or undefined
}
}
null
is a specific value. undefined
is what it will be if it is not passed.
null
是一个特定的值。 undefined
如果它没有通过,它将是什么。
If you just want to know if anything was passed or not and don't care what its value is, you can use arguments.length
.
如果您只想知道是否传递了任何内容并且不关心它的值是什么,您可以使用arguments.length
.
function alertStatement(link) {
if (arguments.length) {
// argument passed
} else {
// argument not passed
}
}