简体   繁体   English

在数组中添加数字。 得到奇怪的输出。 Java脚本

[英]Adding numbers in an Array. Getting weird output. Javascript

    var array = [];        
    getNum();
    document.write(array);
    document.write("<br>Sum: " + sum(array));

    //Function to Sum Array
    function sum(params){
        var total = 0 ;
        for (i = 0; i < params.length; i++){
            total += params[i];
        }
        return total;
    }


    //Function to get Numbers in Array
    function getNum(){
        var count = 0;
        alert("Please enter 5 numbers");
        while(count < 5) {
            array[count] = prompt("Number " + (count + 1));
            count++;
        }
    }

Current Output 电流输出

5,4,3,2,1
Sum: 054321

What I want 我想要的是

5,4,3,2,1
Sum: 15

I'm trying to make a program where the user adds numbers to an Array and the program calculates different things about those numbers. 我正在尝试制作一个程序,其中用户将数字添加到数组,并且该程序计算关于这些数字的不同内容。

When I call sum(array); 当我打电话给sum(array); with a preset array such as var array = [5,4,3,2,1]; 带有预设数组,例如var array = [5,4,3,2,1]; The summing works fine and outputs 15 as expected. 求和可以正常工作,并按预期输出15。
However instead of having a preset array, when I include the function to get the set of numbers for the Array, the summation the output is 054321. 但是,当没有包含预设数组时,当我包含用于获取数组数字集的函数时,输出的总和为054321。

I want to do the array calculations manually for my own understandings sake, rather than using reduce(); 为了自己的理解,我想手动进行数组计算,而不是使用reduce();。

What am I doing wrong? 我究竟做错了什么?

Parse your prompt value as an integer - it's being added as a string and concatenated with the + sign: 将您的提示值解析为整数-将其添加为字符串并以+号串联:

array[count] = parseInt(prompt("Number " + (count + 1)));

http://jsfiddle.net/4kp825tc/ http://jsfiddle.net/4kp825tc/

MDN also recommends to cast as a Number as another option: MDN还建议Number为另一种选择:

Please note that result is a string. 请注意,结果是一个字符串。 That means you should sometimes cast the value given by the user. 这意味着您有时应该转换用户给定的值。 For example, if his answer should be a Number, you should cast the value to Number. 例如,如果他的答案应为数字,则应将值转换为数字。 var aNumber = Number(window.prompt("Type a number", "")); var aNumber = Number(window.prompt(“输入数字”,“”)));

   //Function to Sum Array
    function sum(params){
        var total = 0 ;
        for (i = 0; i < params.length; i++){
            var temp = parseInt(params[i]);
            total += temp;
        }
        return total;
    }

Your inputs are stored as strings in your array. 您的输入以字符串形式存储在数组中。 You'll need to convert the value to a number for the summation to occur correctly. 您需要将值转换为数字,以便正确进行求和。

Use parseInt (set to base 10) to get the correct answer. 使用parseInt(设置为10)以获取正确的答案。

        total += parseInt(params[i],10);

http://jsfiddle.net/biz79/x9cbm7Lj/ http://jsfiddle.net/biz79/x9cbm7Lj/

The values from prompt are strings and thats why the don't add as you wish add plus before params[i] and your have it correct 提示中的值是字符串,这就是为什么不按需添加的原因,在params [i]之前添加加号,然后正确设置

var array = [];        
getNum();
document.write(array);
document.write("<br>Sum: " + sum(array));

//Function to Sum Array
function sum(params){
    var total = 0 ;
    for (i = 0; i < params.length; i++){
        total += +params[i]; //make the params[i] to be a number
    }
    return total;
}


//Function to get Numbers in Array
function getNum(){
    var count = 0;
    alert("Please enter 5 numbers");
    while(count < 5) {
        array[count] = prompt("Number " + (count + 1));
        count++;
    }
}

Here's a one-line solution: 这是一线解决方案:

function sum(params) {
    return params.map(function(item) { return parseInt(item); }).sum()
}

Do everything the same, just parse the user input to an integer. 一切相同,只需将用户输入解析为整数即可。 The issue here is that the numbers are being treated as strings. 这里的问题是数字被视为字符串。

Modify your sum function like this: 像这样修改sum函数:

//Function to Sum Array
function sum(params){
    var total = 0 ;
    for (i = 0; i < params.length; i++){
    $num = parseInt(params[i]);
    total += $num;
    }
    return total;
}

That's it, you're done. 就是这样,您完成了。

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

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