I have a string:
var x = "news";
and I have a variable
var news = array("1", "2", "3");
I really want to check if is there a variable have the same name with the string "news", in this case, it will return true because there is a variable name news
Can I do this in JavaScript?
You can iterate through the keys of this
and check for a var name
var x = "news" var news = ["1", "2", "3"] function varNameExists(varName){ return [...Object.keys(this)].some(name => name === varName) } console.log(varNameExists(x))
You can check with window.hasOwnProperty
but this is not proper way.
var x="news"; var news=["1","2","3"]; console.log(window.hasOwnProperty(x)) x="nxyz"; console.log(window.hasOwnProperty(x)) x="news"; console.log(window.hasOwnProperty(x))
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.