哪种检查变量是否已初始化的方法更好/正确? (假设变量可以保存任何东西(字符串、整数、对象、函数等))
if (elem) { // or !elem
或
if (typeof elem !== 'undefined') {
或
if (elem != null) {
最佳答案
你想要the typeof
operator .具体来说:
if (typeof variable !== 'undefined') {
// the variable is defined
}
关于JavaScript 检查变量是否存在(已定义/初始化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5113374/