我想知道是否可以将元素广告到声明如下的数组中......请检查add()函数,我不知道如何解决这个问题。谢谢
这不是必需的,但如果您给出一个解释,因为 c++ 观点程序员,我将不胜感激。
// My array is this way declared
var myArray = [
['John', 'Doe', '1980'],
['Jane','Malloy','1982'],
['Vincent','Malloy','1972']
];
// then I want to add a new elements in it, but It seems to doesn't work
var add = function() {
//var textbox = document.getElementById('textbox').value;
// storing new person in array
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
};
//finally this function is for displaying the elements of myArray
var show = function() {
// clean output
document.getElementById('output').innerHTML = '';
// delay time
setTimeout (function() {
// showing info. people
for (var i in myArray) {
for (var j in myArray)
document.getElementById('output').innerHTML += myArray[i][j] + ' ';
document.getElementById('output').innerHTML += '<br/>';
}
}, 250);
};
所以就在这里:
var add = function() {
//var textbox = document.getElementById('textbox').value;
// storing new person in array
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
};
无法添加到myArray[3]
,因为myArray[3]
未定义。您需要先为myArray[3]
分配一个空数组:
myArray [3] = [];
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
或者更一般地说,假设这个想法是添加到数组的末尾,您可以执行以下操作:
var idx = myArray.length;
myArray[idx] = [];
myArray[idx][0] = "New 1";
// ...
甚至像这样:
var newArray = ["New1", "New2", "New3"];
myArray.push(newArray);