1

このプログラムを作成して、ユーザーに2つの単語を入力させ、両方の単語を1行に出力しようとしています。行全体の長さが 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>

例:

最初の単語を入力してください:

カメ

2 番目の単語を入力してください

153

(プログラムは以下を出力します)

タートル.................................153

4

5 に答える 5

3

これを行う方法を示す一般的なソリューションを次に示します。

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文字数よりも短いことを確認してください。

于 2012-04-11T13:20:32.567 に答える
1

必要な期間の数を計算する必要があります。

var enteredLength = firstword.length + secondword.length;
var dotCount = 30 - enteredLength;

var dots = "";
for(var i = 0; i < dotCount; i++) dots += '.';

あなたはそこから....

于 2012-04-11T13:20:10.127 に答える
0

30 から最初の単語の長さと 2 番目の単語の長さを引き、その数のドットを for ループで出力します。

于 2012-04-11T13:20:03.563 に答える
0

プロパティを使用してlength各文字列の長さを決定し、.追加する必要がある の数を計算できます。

于 2012-04-11T13:20:27.320 に答える
0

簡単な計算を使用して、ドットの量を取得できます。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 );
于 2012-04-11T13:21:01.317 に答える