如何将二维数组的值输出到文本区域?
我可以访问二维数组的第一个维度,但如何访问第二个维度?我想使用 \t 和 \n 等转义序列以类似表格的方式在文本区域中显示数组的值。
到目前为止我的来源:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
var txt = "";
var Person = new Array(4);
for (var i=0; i<4; i++)
Person[i] = new Array(5);
function display()
{
for (i = 0; i< 4; i++)
{
txt += "Person " + i + \t;
for (var j = 0; j < 5; j++)
txt += Person[i][j] + \t;
txt += \n;
}
document.getElementById("results").innerHTML = txt;
}
</script>
</head>
<body>
<form id="input">
<input type="submit" value="Submit" onclick="display()" /><br />
<textarea id="results" rows="7" cols="39"></textarea>
</form>
</body>
</html>
I can access the first dimension of the two-dimensional array but how would I access the second one? I want to display values of the array in a text-area in a table like way using escape sequences like \t and \n.
My source so far:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
var txt = "";
var Person = new Array(4);
for (var i=0; i<4; i++)
Person[i] = new Array(5);
function display()
{
for (i = 0; i< 4; i++)
{
txt += "Person " + i + \t;
for (var j = 0; j < 5; j++)
txt += Person[i][j] + \t;
txt += \n;
}
document.getElementById("results").innerHTML = txt;
}
</script>
</head>
<body>
<form id="input">
<input type="submit" value="Submit" onclick="display()" /><br />
<textarea id="results" rows="7" cols="39"></textarea>
</form>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
再简单不过了:替换
为
您已将
Person
设为数组的数组。对于Person[i]
,您已经获得了它的第i
元素,它是一个数组。使用Person[i][j]
,您就获得了该内部数组的第j
元素。您也可以这样写:
作为旁注,我会在将文本分配给innerHTML属性之前组装您的文本,这样要快得多:您现在编写的方式意味着每次都要查找文本区域,获取其innerHTML,添加我们的位,并将其重新分配给innerHTML 属性。
Couldn’t be easier: replace
by
You've made
Person
an array of arrays. WithPerson[i]
, you’ve got itsi
th element, which is an array. WithPerson[i][j]
, you’ve got thej
th element of that inner array.You could also write it like this:
As a side note, I’d assemble your text before assigning it to the innerHTML property, it’s a lot faster: the way you’ve written it now means looking up the textarea each time, fetching its innerHTML, adding our bit to it, and reassigning it to the innerHTML property.