首页 > JS怎么判断一个值有没有定义

JS怎么判断一个值有没有定义

想要做一个判断,服务器返回过来的对象有没有某个属性,用if时,若没有返回这个对象,会直接报错.例如在console上if(a){console.log("a")}else{console.log("b")},会报错Uncaught ReferenceError: a is not defined。 而我想让它没有定义的话就直接进入条件句而不是报错。 现在能想到的做法是用if(typeof(a)=="undefined")做判断。
同时还想请教一下,当我用if(typeof(undefined)==undefined)的时候值为false,请问这个时候右边的undefined又是什么,为什么没有报Uncaught ReferenceError: a is not呢?


typeof()里的undefined是变量名,等号后面的是数据类型


先说一个

typeof undefined === "undefined"

而不是undefined,typeof返回的是字符串类型。
其次,判断返回对象有没有某个属性可以用hasOwnProperty这个方法。


在js中如果你对一个值不做定义,怎么f做都是返回not defined,

typeof()的返回值是字符串,该字符串用来说明运算数据类型,一般返回number,boolean,string,function,object,undefined
至于你说的右边的undefined是什么,因为undefined本来就不是一个确定的值,所以

console.log(typeof(undefined) === "undefined") //true
console.log(typeof(undefined) === undefined) //false
console.log(typeof(undefined) == "undefined") // true

a is not的原因是:
1、not defined
未声明
console.log(a) // a is not defined

2、undefined
var a;
声明了,但没赋值
console.log(a); // undefined

如果有错误的地方还望指正,谢谢


The typeof operator returns a string indicating the type of the unevaluated operand.
typeof操作符然返回一个未求值的操作数的类型的字符串表示

typeof操作符的操作数为一个对象或基本类型值,Undefined也是一个基本类型,undefined是这个类型的唯一一个值

if(a){
    console.log("a");
}else{
    console.log("b");
}

会对a求值,如果此时a未定义过,那么就会抛出如下错误
Uncaught ReferenceError: a is not defined是应为a变量没有定义


你现在的想法是对的,但是为什么下面做测试的时候是错的,可能你还不够理解typeof的返回值问题

因为typeof返回的是字符串类型(比如number、string、boolean、object、function、undefined),所以正确的两种写法是

if(typeof(undefined)=="undefined")

另外undefined 表示一个未声明的变量,或已声明但没有赋值的变量,或一个并不存在的对象属性。

补充一下,为了便于你理解undefined其实是一种数据类型你的代码

if(typeof(a)=="undefined")

可以改成类似

var a = undefined;
if(a==undefined){
    alert(true);
}
【热门文章】
【热门文章】