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

相关问题