gpt4 book ai didi

javascript - 我试图在 JavaScript 中添加三个数字的总和,但它给了我 NaN。为什么?

转载 作者:行者123 更新时间:2023-11-28 14:22:05 26 4
gpt4 key购买 nike

我想从用户那里收集三个数字并使用函数和循环添加它们。我不断想出 NaN。为什么是这样?我尝试将字符串提示转换为 Number 对象来解决此问题。

var userEntry1 = Number(window.prompt("Enter in a number of your choice"));
var userEntry2 = Number(window.prompt("Enter in a number of your choice"));
var userEntry3 = Number(window.prompt("Enter in a number of your choice"));
var sum;
var i;
function addNumb(userEntry1, userEntry2, userEntry3) {
"use strict";
sum = userEntry1 + userEntry2 + userEntry3;
for (i = 1; i <= arguments.length; i += 1) {
sum += Number(arguments[i]);

}
return sum;

}

addNumb(userEntry1, userEntry2, userEntry3);
window.console.log(sum);

最佳答案

在循环中,循环的长度等于 arguments 的长度,但由于它是一个基于 0 的数组,因此您的迭代次数太多了。更改<=< :

var userEntry1 = Number(window.prompt("Enter in a number of your choice"));
var userEntry2 = Number(window.prompt("Enter in a number of your choice"));
var userEntry3 = Number(window.prompt("Enter in a number of your choice"));
var sum;
var i;

function addNumb(userEntry1, userEntry2, userEntry3) {
"use strict";
sum = userEntry1 + userEntry2 + userEntry3;
for (i = 0; i < arguments.length; i += 1) {
sum += Number(arguments[i]);

}
return sum;

}

addNumb(userEntry1, userEntry2, userEntry3);
window.console.log(sum);

关于javascript - 我试图在 JavaScript 中添加三个数字的总和,但它给了我 NaN。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54847959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com