微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我不想要它时,javascript将整数转换为字符串

如何解决当我不想要它时,javascript将整数转换为字符串

我有一些用其他几种语言编码的经验,但我对 Javascript 很陌生。 我试图首先生成一个连续整数数组,然后使用单独的函数对数组的内容求和。我能够生成数组没问题,但是当我尝试对内容求和时,数组的元素莫名其妙地转换为字符串。我无法解释为什么会发生这种情况。

感谢任何和所有帮助或建议。谢谢。

// Takes a starting and ending number,and returns an array of every step between.

function range(start,end,step = 1) {
    let iterator = start;
    let array = new Array();
    while(iterator <= end) {
        array.push(iterator);
        iterator += step;
    }
    return array;
}

// Takes an array and calculates the sum of the contents.

function sum(...inputs) {
    let total = 0;
    if(inputs[0] instanceof Array) {     // Test whether the input array is single or multi dimensional
        for(input in inputs[0]) {
            console.log(typeof(input));             // Evaluates to String?????? <<<<<<<<<<<<<<<
            console.log(inputs[0] instanceof Array); // Evaluates to true
            console.log(typeof inputs[0][0]);       // Evaluates to Number

            total += input;
        }
    }
    else {
        for(input in inputs) {
            total += input; // I want this to add numbers together,but it concatenates strings instead.
        }
    }

    return total;        // I want this to return a number,but it returns a string.
}

console.log(sum(range(1,10)));  // Returns string literal "00123456789"

解决方法

for(input in inputs[0]) {

这会遍历对象的属性名称,对于数组,它是字符串 "0""1" 等。

使用 of 循环遍历值(即您放入数组中的数字)。

,

所以我做了一些挖掘,似乎问题来自 for in 循环使用。所以 for in 迭代键而不是值,如果我们想迭代值,我们可以使用 for of 循环,如下所示:

function range(start,end,step = 1) {
    let iterator = start;
    let array = new Array();
    while(iterator <= end) {
        array.push(iterator);
        iterator += step;
    }
    return array;
}

// Takes an array and calculates the sum of the contents.

function sum(...inputs) {
    let total = 0;
    if(inputs[0] instanceof Array) {             
       for(input of inputs[0]) {
            console.log(typeof(input));  
            console.log(inputs[0] instanceof Array);
            console.log(typeof inputs[0][0]);

            total += input;
        }
    }
    else {
        for(input of inputs) {
            total += input;
        }
    }

    return total;        
}

console.log(sum(range(1,10)));  

您可以在此处阅读有关不同 for 循环的更多信息 (https://www.w3schools.com/js/js_loop_for.asp)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。