2017-03-08 54 views
0

請檢查下面的代碼JavaScript的全局對象的字符串Vs的詮釋

var global_var = 1; 
 
hello = 'hello'; 
 
global_novar = 2; 
 

 
(function() { 
 
    global_fromfunc = 3; 
 
}()); 
 

 

 

 
var global = Object.getOwnPropertyNames(window); 
 
    
 
console.log(global_var in global); 
 
console.log(global_novar in global); 
 
console.log(global_fromfunc in global); 
 
console.log(hello in global);

這裏只最後一條語句打印假的控制檯。如果我將任何整數值分配給hello,那麼它將打印爲真。任何人都可以解釋此行爲

+1

什麼是你希望看到的結果? –

+0

我也想知道你是否打算引用in關鍵字的參數。即全球'''global_var'而不是全局''global_var''。 –

+0

謝謝。我在這裏更正了代碼。 – Aniruddha

回答

0

如果指定財產在指定對象in運營商在JavaScript中返回true。

如果使用陣列in操作,因爲你在上面幹什麼,數組的索引將作爲它的屬性,因此,如果數組包含給定指數您的語句將返回true。這就解釋了爲什麼當你給它一個整數時,它返回true(只要數組包含該索引),但是任何字符串都將返回false。

爲了得到所需的結果,可以使用ECMAScript 7中引入的Array.prototype.includes(對於支持它的瀏覽器),或者參考this question以獲取更多方法來檢查給定對象是否包含在數組中。

var global_var = 1; 
 
hello = 'hello'; 
 
global_novar = 2; 
 

 
(function() { 
 
    global_fromfunc = 3; 
 
}()); 
 

 

 

 
var global = Object.getOwnPropertyNames(window); 
 

 
console.log(global.includes('global_var')); 
 
console.log(global.includes('hello')); 
 
console.log(global.includes('global_novar'));  
 
console.log(global.includes('global_fromfunc'));

+0

感謝您指導我'Array.prototype.includes'。現在使用in,如果我hello = 100,那麼console.log(hello in global)返回true。但是,如果hello = 1000,那麼它返回false。 – Aniruddha

+0

這是因爲你的數組''全球'沒有1001項中,所以索引1000不存在數組中,100是。如果索引存在於數組中,'in'將返回true,而不是如果變量'hello'存在。 –

2

Object.getOwnPropertyNames返回屬性名稱數組。 in運算符是交錯的陣列索引,而不是它的string。注意如果我使hello大,足夠,它返回false

var global_var = 1; 
 
hello = 270000000; 
 
global_novar = 2; 
 

 
(function() { 
 
    global_fromfunc = 3; 
 
}()); 
 

 

 

 
var global = Object.getOwnPropertyNames(window); 
 
console.log(global_var in global); 
 
console.log(global_novar in global); 
 
console.log(global_fromfunc in global); 
 
console.log(hello in global);

還要注意的是in是不一樣的作爲數組包含。

+0

:)好的。我沒有想到這一點。也許瀏覽器做一些優化。我會做更多的搜索.. – Aniruddha