JavaScript中in操作符
定義:
in操作符用來判斷某個屬性屬於某個對象,可以是對象的直接屬性,也可以是通過prototype繼承的屬性。(參見hasOwnProperty)
注意事項:
n 對於一般的對象屬性需要用字符串指定屬性的名稱
如:
var mycar = {make: "Honda", model: "Accord", year: 1998};
"make" in mycar // returns true
"model" in mycar // returns true
n 對於數組屬性需要指定數字形式的索引值來表示數組的屬性名稱(固有屬性除外,如length)。
// Arrays
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
0 in trees // returns true
3 in trees // returns true
6 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)
n in的右邊必須是一個對象,如:你可以指定一個用String構造器生成的,但是不能指定字符串直接量的形式:
var color1 = new String("green");
"length" in color1 // returns true
var color2 = "coral";
"length" in color2 // generates an error (color is not a String object)
n 如果你使用delete操作符刪除了一個屬性,再次用in檢查時,會返回false,如:
var mycar = {make: "Honda", model: "Accord", year: 1998};
delete mycar.make;
"make" in mycar; // returns false
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
delete trees[3];
3 in trees; // returns false
n 如果你把一個屬性值設為undefined,但是沒有使用delete操作符,使用in檢查,會返回true.
var mycar = {make: "Honda", model: "Accord", year: 1998};
mycar.make = undefined;
"make" in mycar; // returns true
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
trees[3] = undefined;
3 in trees; // returns true
最後更新:2017-04-02 06:51:26