简体   繁体   English

为什么给数组分配数字会使数组对象成为nan?

[英]why does assigning a number to an array make the array object a nan?

I have the following code: 我有以下代码:

function bytesToMb(arr)
{
    for(var i=0;i<arr.length;arr++)
    {
        var mbs= arr[i]/(1000*1000);

        arr[i]=mbs;
    }

    return arr;
}

after the line arr[i]=mbs executes, the value of arr (the array object itself) becomes NAN. arr[i]=mbs执行后, arr的值(数组对象本身)变为NAN。
why is that???? 这是为什么????

You are incrementing arr, arr + 1 = NaN because array is NaN; 您要递增arr,arr + 1 = NaN,因为数组是NaN; you ought to do i++ in your for loop instead... 你应该在for循环中执行i ++ ...

You're using arr++ instead of i++ as the third clause in your for loop. 您正在使用arr++而不是i++作为for循环中的第三子句。

The type coercion from Array to Number leads to your NaN . ArrayNumber的类型强制导致您的NaN

Change arr++ to i++ arr++更改为i++

function bytesToMb(arr) {
    for (var i = 0; i < arr.length; i++) {
        var mbs = arr[i] / (1024 * 1024); // you should use 1024*1024 here to make it more precise if you need to.
        arr[i] = mbs;
    }
    return arr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM