任务很简单,写入从 1 到 99 的数字,并将其中的所有数字替换为:num (mod 3) =0
与每个 num (mod 5) =0 -> mat
, num ( mod 3=0 && mod 5=0 )
每个垫子,所有其他保持不变。这很简单,但格式很糟糕,所以我想这样做:在每个数字之间插入一个空格,并将每个“特殊”单词(可被 3,5 或两者整除)放在单独的行上。我知道我必须使用 string.prototype.format 但具体如何使用?这是我当前的代码:
<html>
<body>
<p>Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = [];
var res = " ";
for (i=1; i<100; i++){
if (i%3 == 0 && i%5 == 0){
text[i]= "SachMat ";
}
else if (i%3 == 0){
text[i]= 'sach ';
}
else if (i%5 == 0){
text[i]= 'mat ';
}
else {
text[i]= i;
}
var res = res.concat(text[i]);
}
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
最佳答案
试试这个
function myFunction() {
var text = [];
var res = " ";
for (i=1; i<100; i++){
if (i%3 == 0 && i%5 == 0){
text[i]= "<br/>SachMat<br/>";
} else if (i%3 == 0) {
text[i]= 'sach ';
} else if (i%5 == 0){
text[i]= 'mat ';
} else {
text[i]= i;
}
res = res.concat(' ' + text[i]);
}
document.getElementById("demo").innerHTML = res;
}
关于Javascript 字符串格式 - 替换保存在变量中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648629/