I'm working through a fundamentals course on JavaScript. I was given this assignment on arrays:
我正在学习一门关于JavaScript的基础课程。我接到了这个关于数组的作业:
"Using a loop, have the user enter a set of integers using prompt(). Add each entry to an array called myIntegers. Once the user is done entering integers have them enter ‘xxx.’
“使用循环,让用户使用Prompt()输入一组整数。将每个条目添加到一个名为myIntegers的数组中。一旦用户输入完整数,就让它们输入‘xxx’。”
When the user has completed their data entry, provide the sum, average and product (result of multiplication) of the integers"
当用户完成数据输入时,提供整数的总和、平均值和乘积(乘法结果)。
Here's the code I have so far (not including the standard HTML div and script which is on another page):
以下是我到目前为止拥有的代码(不包括另一个页面上的标准HTMLdiv和脚本):
let myIntegers = [];
let input = "";
let average = "";
let sum = "";
let product = "";
while(input !="xxx"){
input = prompt("Add numbers, end using xxx.");
if(input!="xxx"){
myIntegers.push(input);
}
}
console.log(myIntegers);
for(let x = 0; x < myIntegers.length; x++){
average = average + myIntegers[x]
}
document.getElementById("output").innerHTML =
average / myIntegers.length;
for(let y=0; y < myIntegers.length; y++){
sum = sum + myIntegers[y];
}
document.getElementById("output").innerHTML =
sum;
for(let z=0; z < myIntegers.length; z++){
product = product + myIntegers[z];
}
document.getElementById("output").innerHTML =
product * myIntegers;
This code presents "NaN" but the array in the console looks good. I've tried turning the prompt into numbers and I've changed up the order of the elements a dozen times. This code makes logical sense to me (except for the product, I'm not the best at math) but just doesn't output what I want.
此代码显示“NaN”,但控制台中的数组看起来很好。我尝试过将提示符转换为数字,并多次更改元素的顺序。这段代码对我来说是合乎逻辑的(除了这个产品,我的数学不是最好的),但没有输出我想要的东西。
Any help is appreciated!
如有任何帮助,我们不胜感激!
Thanks!
谢谢!
更多回答
优秀答案推荐
The text submitted by the user in the prompt is returned as a string or null. So, to perform any athematic operations on it, we need to parse it into the integer or float data type first.
Also, take care while initialization the variables, as if we define them with "", then the var will act as string type, and the + operation act as concatenation instead of addition.
Ex.Example of var intialized as "" act as string type
用户在提示中提交的文本将以字符串或空的形式返回。因此,要对其执行任何主题操作,首先需要将其解析为整型或浮点型数据类型。此外,在初始化变量时要小心,就像我们用“”定义它们一样,那么var将作为字符串类型,而+运算将作为串联而不是加法。示例初始化为“”的var示例用作字符串类型
You can use the following possible code snippet to perform the same required task.
您可以使用以下可能的代码片段来执行相同的所需任务。
let myIntegers = [];
let input = 0;
let average = 0;
let sum = 0;
let product = 1;
while (input != "xxx") {
input = prompt("Add numbers, end using xxx.");
if (input != "xxx") {
myIntegers.push(input);
}
}
console.log(myIntegers);
for (let y = 0; y < myIntegers.length; y++) {
sum = sum + parseFloat(myIntegers[y]);
product = product * parseFloat(myIntegers[y]);
}
console.log(sum, product, sum/myIntegers.length);
document.getElementById('output').innerHTML = 'sum = '+ sum + ' product = '+ product + ' average = ' + (sum/myIntegers.length);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
let myIntegers = [], input = "", sum = 0, product = 1;
while(input !="xxx"){
input = prompt("Add numbers, end using xxx.");
if(input!="xxx"){
myIntegers.push(input);
}
}
console.log(myIntegers);
for(let x = 0; x < myIntegers.length; x++){
sum = sum + (parseFloat(myIntegers[x]) || 0);
product = product * (parseFloat(myIntegers[x]) || 1);
}
document.getElementById("output").innerHTML = `sum = ${sum}, product = ${product}, avg = ${sum/myIntegers.length}`
<div id="output"></div>
let myIntegers = [];
let input = '';
let average = 0;
let sum = 0;
let product = 1;
while(input !="xxx"){
input = prompt("Add numbers, end using xxx.");
if(input!="xxx"){
myIntegers.push(Number(input));
}
}
console.log(myIntegers);
for(let x = 0; x < myIntegers.length; x++){
average += myIntegers[x];
}
console.log(average / myIntegers.length);
for(let y=0; y < myIntegers.length; y++){
sum += myIntegers[y];
}
console.log(sum);
for(let z=0; z < myIntegers.length; z++){
product *= myIntegers[z];
}
console.log(product);
I've tried to leave the code as closer to one that you wrote as possible. I've just modified the DOM methods adding the console.log()
and modified the arithmetic operators with the assignment operators.
我已经尽量使代码更接近于您编写的代码。我刚刚修改了DOM方法,添加了console.log(),并用赋值运算符修改了算术运算符。
That said, I think I found 2 main problems:
我发现了两个主要问题:
The prompt()
method returns a string
so, if you don't convert that string
to a number
, every successive arithmetic operation done with the for
loops will be executed with the strings (that's why I used the Number()
method inside the if
statement block). And there are problems when you execute arithmetic operations with the strings (the +
operator it is used to concatenate strings and if you try to use it in a context like 1 + '1'
you will end with possible unexpected results like '11'
and not 2
because it will convert the previous or following operand in a string, if there is any string around in the expression (e.g. 1 + 1 + '1'
is '21'
and '2' + 1 + 1
is '211'
). Any other operation will work as expected (e.g. '3' * 2
will be 6
and not '32'
). More info here https://www.w3schools.com/js/js_numbers.asp ).
The second problem, correlated with the first one, it is about your average
, sum
and product
variable initialisation. They are initialised with an empty string and every operation performed on an empty string (be it, well, a string
!) will follow the rules stated at point 1.
Have a good day!
祝你今天愉快!
更多回答
我是一名优秀的程序员,十分优秀!