JavaScript检查变量是否存在(定义/初始化)检查变量是否已初始化的哪种方法更好/更正?(假设变量可以包含任何内容(字符串,整数,对象,函数等))if (elem) { // or !elem要么if (typeof(elem) !== 'undefined') {要么if (elem != null) {
3 回答
月关宝盒
TA贡献1772条经验 获得超5个赞
该typeof运营商将检查变量确实是不确定的。
if (typeof variable === 'undefined') {
// variable is undefined}该typeof运营商,不同于其他运营商,不会抛出的ReferenceError与未声明的变量使用时例外。
但是,请注意typeof null将返回"object"。我们必须小心避免将变量初始化为错误null。为了安全起见,这是我们可以使用的:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null}添加回答
举报
0/150
提交
取消
