Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

while loop - 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..

question from:https://stackoverflow.com/questions/65546238/please-help-me-im-a-beginner-at-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...