需要循环帮助来使用 Javascript 构建表
这是我的函数:
function CreateResultsTable(bps, incs) {
var table = document.createElement('table');
var str = '<table border=1>';
str += '<tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th></tr>';
var i = 0;
// up
for (i = 0; i < incs; i++) {
var num = (incs - i) * bps;
var newStr = num.toString();
str += '<tr><th>' + newStr + '</th><td>100,000</td><td>100,000</td><td>100,000</td><td>100,000</td><td>100,000</td></tr>';
}
i = 0;
//down
for (i = incs; i > 0; i--) {
var num = (incs - i) * bps;
var newStr = '-' + num.toString();
str += '<tr><th>' + newStr + '</th><td>100,000</td><td>100,000</td><td>100,000</td><td>100,000</td><td>100,000</td></tr>';
}
return str;
}
我想要的是说我传入 {bps = 25, incs = 4}
。它应该始终创建两倍于 incs 的行数(在标题行下方)。因此,对于 incs = 4
和 bps = 25
,它应该创建第一个 td = 100, 75, 50, 25, -25, -50, - 的行75、-100——按此顺序。
它现在所做的就是创建像 100, 75, 50, 25, -0, -25, -50
这样的值 - 就是这样。
我做错了什么?
Here is my function:
function CreateResultsTable(bps, incs) {
var table = document.createElement('table');
var str = '<table border=1>';
str += '<tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th></tr>';
var i = 0;
// up
for (i = 0; i < incs; i++) {
var num = (incs - i) * bps;
var newStr = num.toString();
str += '<tr><th>' + newStr + '</th><td>100,000</td><td>100,000</td><td>100,000</td><td>100,000</td><td>100,000</td></tr>';
}
i = 0;
//down
for (i = incs; i > 0; i--) {
var num = (incs - i) * bps;
var newStr = '-' + num.toString();
str += '<tr><th>' + newStr + '</th><td>100,000</td><td>100,000</td><td>100,000</td><td>100,000</td><td>100,000</td></tr>';
}
return str;
}
What I want is say I pass in {bps = 25, incs = 4}
. It should always create double the amount of rows (underneath the header row) of incs. So for incs = 4
and bps = 25
, it should create rows with first td = 100, 75, 50, 25, -25, -50, -75, -100
-- in that order.
What it's doing now is creating them like 100, 75, 50, 25, -0, -25, -50
-- and that's it.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最后一个循环需要是
>=
而不是只是>
并开始一个较低的循环,如下所示:您可以在此处进行测试,唯一的其他更改是在末尾添加
以及引号你的边框属性。
不过,有一种更简单的方法可以解决此问题,使用单个循环并根据需要排除
0
,如下所示:您可以在这里测试结果,这只是一种更简单/更便宜的单循环方式或做同样的事情。
You last loop needs to be
>=
instead of just>
and start one lower, like this:You can test it out here, the only other change is a
</table>
addition at the end and quotes on your border attribute.There is a much simpler way to go about this though, use a single loop and exclude
0
if you want, like this:You can test the result here, it's just a simpler/cheaper single-loop way or doing the same thing.
您必须从
incs -1
开始并数到零。所以这个函数应该看起来像You have to start at
incs -1
and to count to zero. So the function should look like