下面是Instanceof运算符的示例。
例子:
<!DOCTYPE html>
< html >
< body >
< center >
< h1 style = "color:green" >lsbin</ h1 >
< p id = "GFG" ></ p >
< script >
var a = ["Geeks", "for", "Geeks"];
document.getElementById("GFG").innerHTML =
(a instanceof Array) + "< br >" +
(a instanceof Number);
</ script >
</ center >
</ body >
</ html >
输出如下:
运算符实例JavaScript中的ins用于在运行时检查对象的类型。它返回一个布尔值如果为true, 则表明该对象是特定类的实例;如果为false, 则它不是.
语法如下:
var gfg = objectName instanceof objectType
参数:
objectName: 说明对象的名称。
示例1:objectTypes。
<!DOCTYPE html>
< html >
< body >
< center >
< h1 style = "color:green" >lsbin</ h1 >
< p id = "GFG" ></ p >
< script >
var fruits = ["Apple", "Mango", "Banana"];
document.getElementById("GFG").innerHTML =
(fruits instanceof Array) + "< br >" +
(fruits instanceof Object) + "< br >" +
(fruits instanceof String) + "< br >" +
(fruits instanceof Number);
</ script >
</ center >
</ body >
</ html >
输出如下:
示例2:证明String和Date对象也是Object的一种(从Object派生)。
<!DOCTYPE html>
< html >
< body >
< h1 style = "color:green" >lsbin</ h1 >
< p id = "GFG" ></ p >
< script >
var myString = new String();
var myDate = new Date();
console.log(myString instanceof Object);
console.log(myString instanceof Date);
console.log(myString instanceof String);
console.log(myDate instanceof Date);
console.log(myDate instanceof Object);
console.log(myDate instanceof String);
</ script >
</ body >
</ html >
输出如下
支持的浏览器:
- 谷歌浏览器
- 火狐浏览器
- 边缘
- 歌剧
- 苹果Safari