JavaScript—关系操作符:in、instanceof

来源:互联网 发布:袁和平 知乎 编辑:程序博客网 时间:2024/05/18 14:45

关系操作符(Relational operators)

关系操作符对操作数进行比较,根据比较结果相等与否,返回相应的布尔值。

in

in operator, 如果指定的属性(property)在指定的对象(object)中会返回true,语法如下:

propNameOrNumber in objectName

propNameOrNumber在这里可以是一个代表着属性名的字符串或者是一个代表着数组索引的数值表达式,而objectName则是一个对象名.

下面的例子是 in 操作的常见用法.

// Arraysvar trees = new Array("redwood", "bay", "cedar", "oak", "maple");0 in trees;        // returns true3 in trees;        // returns true6 in trees;        // returns false"bay" in trees;    // returns false (you must specify the index number,                   // not the value at that index)"length" in trees; // returns true (length is an Array property)// Predefined objects"PI" in Math;          // returns truevar myString = new String("coral");"length" in myString;  // returns true// Custom objectsvar mycar = {make: "Honda", model: "Accord", year: 1998};"make" in mycar;  // returns true"model" in mycar; // returns true

instanceof

instanceof operator, 如果对象是某种指定类型(object type)返回true.语法如下:

objectName instanceof objectType

objectName 是对象的名称相较于objectType,objectType是对象的类型, 例如Date或 Array.

当你需要确认一个对象在运行时的类型时使用instanceof.例如, 抓取异常, 你可以根据抛出异常的类型分类处理异常代码.

例如, 下面的代码使用instanceof去判断 theDay是否是一个 Date 对象. 因为theDay是一个Date对象, 所以if中的代码会执行.

var theDay = new Date(1995, 12, 17);if (theDay instanceof Date) {  // statements to execute 执行}
0 0
原创粉丝点击