typeof运算符
typeof 运算符有助于获取其操作数的数据类型。
操作数可以是文字或者数据结构(对象、函数或者变量)。
typeof 函数返回一个带有变量类型名称的字符串作为第一个参数(对象、布尔值、未定义等)。
typeof函数
大多数开发人员使用 typeof 方法来检查属性的类型是否未定义。
如果对象具有未定义值的属性,则不推荐使用 typeof。
let myObj = { welcome: "Welcome" }; if ("undefined" === typeof (myObj["welcome"])) { //The property DOESN'T exists console.log(undefined); } else { //The property exists console.log(myObj["welcome"]); }
let myObj = { welcome: "Welcome" }; if ("undefined" === typeof (myObj.welcome)) { //The property DOESN'T exists console.log(undefined); } else { //The property exists console.log(myObj.welcome); }
hasOwnProperty 方法
Javascript 对象提供了 hasOwnProperty 本机方法。
该方法返回一个布尔值,指示对象是否具有指定的属性作为第一个参数。
hasOwnProperty 方法不会检查对象的原型链。
let myObj = { welcome: "Welcome to onitroad." }; let prop = myObj.hasOwnProperty("welcome"); if (prop) { //myObj has the welcome property console.log(prop); } else { //myObj doesn't have welcome property console.log(prop); } //False let hasPropertyWelcome = myObj.hasOwnProperty("Javascript"); //Use hasOwnProperty in arrays too using the index console.log(["welcome"].hasOwnProperty(0)); //true //But no the value console.log(["welcome"].hasOwnProperty("welcome")); //false
in 运算符
如果 in 运算符在对象中找到指定的属性,则返回 true。
in 运算符可用于对象和数组。
let myObj = { welcome: "Welcome to onitroad" }; let prop = "welcome" in myObj if (prop) { //Welcome property exists console.log(prop); } else { //Welcome property exists console.log(prop); } //False let isInObject = ("hi" in myObj); //Use in in arrays too using the index console.log((0 in ["welcome"])); //true //But not the value console.log(("welcome" in ["welcome"])); //false
要了解哪种方法更快,我们应该使用大型对象。
测试表明 typeof 比 hasOwnProperty 和 in 方法快得多。
在 JavaScript 中有多种方法可以检查对象是否具有属性。
hasOwnProperty 与 in
hasOwnProperty 方法返回一个布尔值,显示对象是否包含指定的属性。
此方法确定对象是否具有指定的属性作为该对象的直接属性。
与 in 运算符不同,hasOwnProperty 不检查对象原型链中的属性。
如果一个对象是一个数组,这个方法可以检查一个索引是否存在。
如果指定的属性存在于对象或者其原型链中,则 in 运算符返回 true。
日期:2020-06-02 22:16:10 来源:oir作者:oir