【问题标题】:Create custom numeric arrays index in Javascript在 Javascript 中创建自定义数值数组索引
【发布时间】:2023-03-30 21:02:01
【问题描述】:

我尝试在 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

如果 typeof 是 object 而不是 undefined,为什么要创建两次 map[10]

【问题讨论】:

    标签: javascript arrays object typeof


    【解决方案1】:

    在这一行你需要移动()

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

    应该是:

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

    这一行也是如此:

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

    您正在寻找比较的类型,它总是会评估为字符串'boolean',这将评估为真。

    【讨论】:

      【解决方案2】:

      typeof 将 tyoe 作为字符串返回,因此类型检查将类似于

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

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

      而且typeof 中不需要() 来包装您要检查的项目,它是keyword,而不是function。当您包装表达式(在您的情况下为map[posx]===undefined)时,在 typeof 中使用() 意味着执行该表达式的偏好更高,并且将根据该结果检查类型。所以表达式解析map[posx]===undefined首先解析,您正在检查resule的类型truefalse

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-09
        • 1970-01-01
        • 1970-01-01
        • 2019-09-02
        • 2010-11-05
        • 2014-03-22
        • 1970-01-01
        相关资源
        最近更新 更多