javascript - 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.
解决方案
请记住,第一个参数/参数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]));
推荐阅读
- javascript - React Konva - 代码突然运行
- memory-leaks - Ratchet + Symfony 3.4 - 释放内存
- mysql - MySQL安装错误:初始化数据库
- android - 我正在尝试从 qr 代码中检索数据并将其放入我的 firestore 数据库中。我目前正在使用 google firebase 的 ML kit 扫描仪
- python - 在 Ubuntu 14 上安装 saleor 时 pip install Valuerror
- javascript - Javascript - 对象字段未定义
- r - 从 R 对象中选择 ID
- c++ - 为什么这种类型的双关语不是未定义的行为?
- ssl - 与 HTTPS 网页的无保护连接
- ipad - 带有 macOS 10 的 VMware 14 无法识别 iPad 10.5