问题描述
我有一些用其他几种语言编码的经验,但我对 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)