JavaScript 中的 instanceof 运算符
JavaScript 中的 instanceof 运算符在运行时环境中检查对象的类型。它返回的结果是布尔类型,即如果给定的输入对象与正在检查的对象相同,则返回“true”,否则返回“false”。
语法
instanceof 运算符的语法如下所示:
var myVar = nameOfObject instanceof typeOfObject
instanceof 运算符在 JavaScript 中用于一个独特的目的。在 JavaScript 中,一些变量声明时没有提及变量类型或数据类型。在 C、C++、Java 中,必须声明变量的数据类型。因此,在 JavaScript 中,为了知道声明的变量的数据类型,我们使用 instanceof 运算符,以便可以知道变量的类型是对象还是任何数据类型。
示例 1
此示例演示了在 JavaScript 中使用instanceof 运算符:
<!DOCTYPE html> <html> <body> <p id="arr1"></p> <p id="TP"></p> <script> var arr = ["Tutorials", "Point", "Articles"]; document.getElementById("arr1").innerHTML = "The given input is: " + arr + " type is: " + typeof(arr) document.getElementById("TP").innerHTML = "Check the instance of given object" + "<br>" + "For Array: " + (arr instanceof Array) + "<br>" + "For Number: " + (arr instanceof Number); </script> </body> </html>
示例 2
以下是此运算符的另一个示例:
<!DOCTYPE html> <html> <body> <p id="arr1"></p> <p id="TP"></p> <script> var departments = ["IT", "CSE", "ECE", "EEE"]; document.getElementById("arr1").innerHTML = "The given input is: " + departments + " and type of: " + typeof(departments) document.getElementById("TP").innerHTML = "Checking the instance of given object with different data types " + "<br>" + "for Array: " + (departments instanceof Array) + "<br>" + "for String: " + (departments instanceof String) + "<br>" + "for Object: " + (departments instanceof Object) + "<br>" + "for Number: " + (departments instanceof Number); </script> </body> </html>
示例 3
使用字符串和日期
现在,让我们看看使用 instanceof 运算符与字符串和日期对象。
<!DOCTYPE html> <html> <body> <p id="ds"></p> <p id="TP"></p> <script> var Str = new String(); var Dt = new Date(); document.getElementById("ds").innerHTML = "The given input is: " + Dt + Str + " type of: " + typeof(Dt) + " " + typeof(Str) document.getElementById("TP").innerHTML = "Checking the instance of given objects with different data types: " + "<br>" + "with given Str for Object " + (Str instanceof Object) + "<br>" + "with given Str for Date: " + (Str instanceof Date) + "<br>" + "with given Str for String: " + (Str instanceof String) + "<br>" + "with given Dt for Date: " + (Dt instanceof Date) + "<br>" + "with given Dt for Object: " + (Dt instanceof Object) + "<br>" + "with given Dt for String: " + (Dt instanceof String); </script> </body> </html>
示例 4
使用原始值
字符串和数字是原始值,而不是对象,因此没有 [[Prototype]],所以只有将它们包装在普通对象中才能工作。
console.log(1 instanceof Number) console.log(new Number(1) instanceof Number) console.log("" instanceof String) console.log(new String("") instanceof String)
示例 5
可构造函数
返回其对象的函数(JS 类)可以使用 instanceof 运算符检查其对象。
function Person(name) { this.name = name } let john = new Person("John"); console.log(john instanceof Person)
示例 6
继承
JS 支持原型继承,因此如果您检查层次结构中任何类的 instanceof,它将返回 true。
class Person {} class Student extends Person { constructor(name) { super() this.name = name } } let john = new Student("John"); console.log(john instanceof Person) console.log(john instanceof Student)
广告