2017-07-26 90 views
0

我嘗試在Javascript中創建受欺騙的索引。這是我的代碼。在Javascript中創建自定義數值數組索引

var map = []; 

function createIndexIfNotExists (posx,posy){    
if(typeof(map[posx]===undefined)){ 
      map[posx] = {}; 
      console.log("created: map["+posx+"] typeof="+typeof(map[posx])); //typeof object 
} 

if(typeof(map[posx][posy]===undefined)){ 
      map[posx][posy] = []; 
      console.log("created: map["+posx+"]["+posy+"] 
typeof="+typeof(map[posx])); //typeof object 
} 
map[posx][posy].push({'posx':posx, 'posy':posy }); } 

createIndexIfNotExists(10,5); 
createIndexIfNotExists(10,6); 

但結果是這樣的。

created: map[10] typeof=object 
created: map[10][5] typeof=object 
created: map[10] typeof=object 
created: map[10][6] typeof=object 

爲什麼要創建map[10]兩次,如果是typeof運算和objectundefined

回答

0

在此行中,你需要移動()

if(typeof(map[posx]===undefined)){

應該是:

if(typeof(map[posx])===undefined){

這同樣適用於這一行真:

if(typeof(map[posx][posy])===undefined){

您正在查找將始終評估爲字符串​​的比較類型,該字符串將評估爲true。

0

typeof回報tyoe作爲一個字符串,所以類型檢查會像

if(typeof(map[posx])==="undefined") 

if(typeof(map[posx][posy])==="undefined") 

,也是()typeof不需要包裝的項目你將要檢查,其keyword,尼特function。當你在typeof中包裝一個表達式(map[posx]===undefined)時,機智()意味着執行該表達式的優先級更高,並且將根據該結果檢查類型。所以表達式首先解決map[posx]===undefined,並且您正在檢查結果的類型truefalse

相關問題