Javascript - Line total
Javascript - Line total
我正在尝试创建这个程序来提示用户输入两个单词,然后在一行上打印出两个单词。单词将由足够的点分隔,以便总行长度为 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 );
相关文章:
- Javascript运行Total保持添加
- 使用running total时使用Javascript$NaN
- 在添加的输入字段中计算TOTAL
- Teechart HTML5/Javascript价值股票代码将保留在Tee.Line系列上
- Mustache js line break
- Animating jsplumb line
- Magic Line在使用键盘上下移动时未使用fullPage.js进行更新
- Extjs 4 new line
- 使用d3.js在绑定数据内数组(以恒定性动态生成d3.svg.line)
- BabylonJS Drawing a Line
- "TokenMismatchException in VerifyCsrfToken.php line 53:
- XMLHttpRequest onprogress total在Chrome上始终为0
- Pure WebGL Dashed Line
- D3 Line.Defined不绘制零值
- Opencart - jQuery cart total update - 修改输出
- Line jQuery plugin
- CodeMirror javascript Gutter line Number padding
- add(1)(2)(3).total === 6 - 有没有人见过像这样使用的自返回函数
- Javascript - Line total
- 基本Javascript-试图在For循环中实现一个正在运行的total