[英]How can I test if a variable is set using typeof?
我試圖使用typeof來確定變量是否未定義:
function reset_textarea(reset) {
if (typeof(reset) != 'undefined') {
...do stuff
}
}
我這樣稱呼它:
reset_textarea('hello');
它不起作用,我似乎無法弄清楚為什么。 如果我刪除if語句,函數會正常觸發,因此 - 問題似乎在於我測試變量是否設置的方式。 知道發生了什么事嗎?
好吧,定義了typeof("hello")
( 字符串的類型)。 這是一個String
。 typeof(hello)
(注意缺少引號)就是你所需要的。 這對你有用嗎?
if(typeof(window[reset]) !== 'undefined') {
//...
}
您必須了解變量( hello
)和字符串( "hello"
)之間的區別。 請記住, window["hello"]
等同於window.hello
,但更靈活。
您可以在window
上測試是否存在具有指定名稱的屬性:
function reset_textarea(reset) {
if (typeof(window[reset]) !== 'undefined') {
// ...do stuff
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.