返回NaN的数组数组 [英] Array of array returning NaN

查看:56
本文介绍了返回NaN的数组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么为什么myarray [bla] [bl]总是等于NaN?如果我用1维做同样的事情(myarray [bla]),我会得到这个数字。

So why myarray[bla][bl] always equal to NaN? If I do the same thing with 1 dimension (myarray[bla]), I get the number.

var bla = 'blabla';
var bl = 'bla';
var myarray = [];
for (i = 0; i < 10; i++) {
    if (!myarray[bla]) {
        myarray[bla] = [];
    }
    myarray[bla][bl] += i;
    console.log(myarray[bla][bl] + " + " + i);
}​


推荐答案

好的,让我们一步一步通过你的循环,用字符串值'blabla'替换变量 bla 的实例:

Ok, so let's step through your loop, replacing instances of the variable bla with the string value of 'blabla':

if (!myarray['blabla']) {
  myarray['blabla'] = [];
}

javascript中的数组是整数值的索引。您的代码在这里做的是将一个expando属性添加到名为 blabla 的数组实例中。那就是:

Arrays in javascript are index by integer values. What your code here is doing is adding an expando property to the array instance named blabla. That is:

myarray.blabla = [];

现在重新考虑你的增量声明:

now reconsider your increment statement:

myarray['blabla'][bl] += i;

或者,使用expando属性:

or, with the expando properties:

myarray.blabla.bl  // remember that "myarray.blabla" is set to the empty array above

这是尝试在空数组上访问名为 bl 的属性。这就是你在这里获得 undefined 的原因。

What this is trying to do is access the property named bl on the empty array. That's why you're getting undefined here.

无论如何,作为最佳实践,你可能想避免使用像哈希表这样的javascript数组,因为这样的问题必然会在足够的时间后出现。

Anyway, as a best practice, you might want to avoid using arrays in javascript like hashtables, since problems like this are bound to crop up after enough time.

这篇关于返回NaN的数组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆