首页 > 解决方案 > The result is not a number

问题描述

Please help. What's wrong with this code? The task is follows:

"Write a JavaScript code to divide an given array of positive integers into two parts. First element goes to first part, second element goes to second part, and third element goes to first part and so on. Now compute the sum of two parts and store into an array of size two."

This is my code:

function divArr(arr85) {
    let result = [0, 0]
    arr85.map(function(v, ind) {
        if (ind % 2 != 0) {
            result[0] += v[ind];
        } else if (ind % 2 == 0) {
            result[1] += v[ind];
        }
    })
    return result;
}

The reply is [NAN,NAN].

I can't find the error.

标签: javascriptarraysfunction

解决方案


请记住,第一个参数/参数Array.prototype.map()是指数组中的项目,而不是数组本身。因此,您只需要 doresult[0] += v而不是result[0] = v[ind],例如。

请参阅下面的概念验证代码:

function divArr(arr85) {
    let result = [0, 0]
    arr85.map(function(v, ind) {
        if (ind % 2 != 0) {
            result[0] += v;
        } else if (ind % 2 == 0) {
            result[1] += v;
        }
    })
    return result;
}

console.log(divArr([1,2,3,4,5,6]));


推荐阅读