How to output value of a two dimensional array to a text area?
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);
f开发者_开发知识库unction 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>
Couldn’t be easier: replace
<!-- stuck here -->
by
Person[i][j];
You've made Person
an array of arrays. With Person[i]
, you’ve got its i
th element, which is an array. With Person[i][j]
, you’ve got the j
th element of that inner array.
You could also write it like this:
var array = Person[i];
innerHTML += array[j];
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.
精彩评论