简体   繁体   中英

Please help me .I'm a beginner at JavaScript

i wanna make like this

function(2231)
'8 = 2 + 2 + 3 + 1'

so i will using substring method can extract step by step, and will using while method

let str = String(num);
let first = 0;
let second = first + 1;

while( 0 <= str.length){
str.substring(first, second)
first ++
}

but.. i wanna save str.substring's result one by one, and '+', return..

how to i get result? please advice to me..

substring is required?
Or can you do something like this?

function sum(num) {
  var str = String(num);
  var numbers;
  var total = 0;
  for (var i = 0; i < str.length; i++) {
    total += parseInt(str[i]);
    if (i == 0) {
      numbers = str[i]
    } else {
      numbers += " + " + str[i]
    }
  }
  
  return total + " = " + numbers
}

t = sum("2231");
console.log(t)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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