简体   繁体   中英

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:

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. Any idea what is going on?

Well, typeof("hello") (type of string ) is defined. It's a String . typeof(hello) (note missing quotes) is what you need. Does this work for you?

if(typeof(window[reset]) !== 'undefined') {
  //...
}

You must understand the difference between a variable ( hello ) and a string ( "hello" ). Remember that window["hello"] is equivalent to window.hello , but more flexible.

You can test for the existence of a property with the specified name on window :

function reset_textarea(reset) {

    if (typeof(window[reset]) !== 'undefined') {
       // ...do stuff
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM