[英]How can I test if a variable is set using typeof?
Im trying to use typeof to determine whether or not a variable is undefined: 我试图使用typeof来确定变量是否未定义:
function reset_textarea(reset) {
if (typeof(reset) != 'undefined') {
...do stuff
}
}
Im calling it like this: 我这样称呼它:
reset_textarea('hello');
Its not working and I can't seem to figure out why. 它不起作用,我似乎无法弄清楚为什么。 The function fires normally if I remove the if statement, thus - the issue seems to lie in the way I am testing whether or not the variable is set.
如果我删除if语句,函数会正常触发,因此 - 问题似乎在于我测试变量是否设置的方式。 Any idea what is going on?
知道发生了什么事吗?
Well, typeof("hello")
(type of string ) is defined. 好吧,定义了
typeof("hello")
( 字符串的类型)。 It's a String
. 这是一个
String
。 typeof(hello)
(note missing quotes) is what you need. typeof(hello)
(注意缺少引号)就是你所需要的。 Does this work for you? 这对你有用吗?
if(typeof(window[reset]) !== 'undefined') {
//...
}
You must understand the difference between a variable ( hello
) and a string ( "hello"
). 您必须了解变量(
hello
)和字符串( "hello"
)之间的区别。 Remember that window["hello"]
is equivalent to window.hello
, but more flexible. 请记住,
window["hello"]
等同于window.hello
,但更灵活。
You can test for the existence of a property with the specified name on window
: 您可以在
window
上测试是否存在具有指定名称的属性:
function reset_textarea(reset) {
if (typeof(window[reset]) !== 'undefined') {
// ...do stuff
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.