Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...