问题
I am not sure if I am doing some mistake or is it a default behaviour. I am using splice/unshift to add a new element on top of a 2d array and then try to render that array to a table.
for (var i = 0; i < arr1[i].length; i++) {
for (var j = 0; j < arr1.length; j++) {
var r = arr1[j][i];
dt(r);
}
dttop(i);
}
function dt(x) {
if (isFinite(x) == true) {
numeric++;
} else {
str++;
}
}
function dttop(x) {
if (numeric > str)
arr1.splice(0, 0, "number");
else
arr1.splice(0, 0, "string");
}
alert(arr1); // alert--1
// render the result into html table
s = '<table border=0>';
for (var i = 0; i < arr1.length; i++) {
s = s + '<tr>';
for (var j = 0; j < arr1[i].length; j++) {
s = s + '<td><font size="1" face="Verdana">' + arr1[i][j] + '</font></td>';
}
s = s + '</tr>';
}
s = s + '</table>';
renderArea.innerHTML = s;
So, when I use javascript splice() or unshift(). I get an output like this


Please help
回答1:
From what I can see you are using .splice()
to add the string "number"
or "string"
to the start of the arr1
array. Doing this means that as you loop through to add the values the code tries to access an index of the strings (arr1[i][j]
), resulting in undefined
.
回答2:
I am using splice/unshift to add a new element on top of a 2d array and then try to render that array to a table.
The splice() method returns an array containing the elements that were removed from the original array. If you want to prepend values given a two dimensional array:
var num_arr = [[1,2,3]];
A simpler solution would be:
json_arr = JSON.stringify(num_arr).replace("[[","[0,[");
And rendering to a table would be:
function rowMaster(value,index)
{
return "<tr><td>value</td></tr>".replace("value",value);
}
function parseFarce(value,index)
{
if(typeof value == "number") return "<th>value</th>".replace("value",value);
else if(delete value.length === false && delete value[-1] === true && JSON.stringify(([]).constructor().valueOf()) === "[]")
{
return value.map(rowMaster);
}
else
{
return value;
}
}
JSON.parse(json_arr).map(parseFarce);
References
- JSON.parse Examples
来源:https://stackoverflow.com/questions/23173003/unable-to-render-an-array-into-table-after-splice-and-unshift-in-javascript