我正在创建一个函数,它将函数中提供的所有数字相加。因此,如果输入是1148 = 1 + 1 + 4 + 8 = 14
然而,如果数字是负数,我就卡住了,这应该将第一个数字算作负数。例如:-316 = -3 + 1 + 6 = 4
我所做的是,我尝试拆分并将数字转换为字符串,然后再转换为数字,以将它们相加。但是,由于某些原因,它不会将负数相加,而是返回NaN。
function addNumbers(num) {
var strNum = num.toString();
strNum = strNum.split('');
var total = 0;
for(var i = 0; i < strNum.length; i++){
total += parseInt(strNum[i]);
}
return total;
}
var output = addNumbers(1148);
console.log(output); // --> 14
var output2 = addNumbers(-316);
console.log(output2); // --> should return 4 instead returned NaN
有没有办法解决这个问题,然后用一些负片把它们加起来?
发布于 2017-09-02 11:18:29
function addNumbers(num) {
var isNeg = num < 0, negative
numbers = (isNeg? String(num).slice(1) : String(num)).split('').map(Number);
if (isNeg) numbers[0] *= -1;
return numbers.reduce(function(a,b){ return a + b; });
}
var output = addNumbers(1148);
console.log(output); // --> 14
var output2 = addNumbers(-316);
console.log(output2);
发布于 2017-09-02 11:19:34
您将字符'-‘与数字相加,这样就得到了NaN。在第二种情况下,数组strNum包含'-‘作为第一个元素,然后将其添加到numbers中。你可以这样做:
function addNumbers(num) {
var strNum = num.toString();
strNum = strNum.substr(strNum.indexOf('-')+1).split(''); //split the string after the indexof '-'.
var total = num < 0 ? -strNum[0] : +strNum[0]; //initialize total as positive of first char or negative by checking num<0.
for(var i = 1; i < strNum.length; i++){ //start iteration from second element in array.
total += parseInt(strNum[i]);
}
return total;
}
var output = addNumbers(1148);
console.log(output); // --> 14
var output2 = addNumbers(-316);
console.log(output2); // --> should return 4 instead returned NaN
发布于 2017-09-02 11:34:57
我的评论令人困惑,所以这里有一些实际的代码:)
其思想是将负号解析为一个数字,该数字返回NaN。
function addNumbers(num) {
// remove negative sign so it doesn't get parsed by itself
var numStr = num.toString().split('').replace("-","");
// add negative sign back if needed
if (num < 0) numStr[0] = "-" + numStr[0];
// rest of function
}希望这能有所帮助!
https://stackoverflow.com/questions/46010123
复制相似问题