Javascript - Line total

Javascript - Line total

本文关键字:total Line Javascript      更新时间:2023-09-26

我正在尝试创建这个程序来提示用户输入两个单词,然后在一行上打印出两个单词。单词将由足够的点分隔,以便总行长度为 30。我已经试过了,似乎无法理解。

<html>
<head>
<title>Lenth of 30</title>
<script type="text/javascript">
//Program: Lenth of 30
//Purpose: The words will be separated by enough dots so that the total line length is 30: 
//Date last modified: 4/11/12 
var firstword = ""
var secondword = ""
firstword = prompt("Please enter the first word.")
secondword = prompt("Please enter the second word.")
document.write(firstword + secondword)

</script>
</head>
<body>
</form>
</body>
</html>

举个例子:

输入第一个单词:

输入第二个单词

153

(程序将打印以下内容)

....................153

下面是一个通用解决方案,向您展示如何执行此操作:

function dotPad(part1, part2, totalLength) {
  // defaults to a total length of 30
  var string = part1 + part2,
      dots = Array((totalLength || 30) + 1).join('.');
  return part1 + dots.slice(string.length) + part2;
}

按如下方式使用它:

dotPad('foo', 'bar'); // 'foo........................bar'

在您的情况下:

dotPad(firstword, secondword);

这是一个非常简单的解决方案 — 如果需要,请验证输入字符串的串联形式是否短于 length 个字符。

您需要

计算需要多少个周期。

var enteredLength = firstword.length + secondword.length;
var dotCount = 30 - enteredLength;
var dots = "";
for(var i = 0; i < dotCount; i++) dots += '.';

你可以从那里拿走。

从 30 中减去第一个单词的长度和第二个单词的长度,然后在 for 循环中打印出这么多点。

可以使用

length 属性来确定每个字符串的长度,然后计算需要添加的.数。

您可以使用一些简单的数学运算来获得点的数量。 从 30 中减去每个单词长度。

var dotLen = 30 - firstword.length - secondword.length;
document.write( firstword );
while ( dotLen-- ) {
    document.write( "." );
}
document.write( secondword );

编辑:我实际上更喜欢Mathias的解决方案。但你可以让它更简单:

document.write( firstword + Array( 31 - firstword.length - secondword.length ).join( '.' ) + secondword );