嗨我想知道它是否可能将广告元素添加到数组中,并声明如下... 请检查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';
};
//finnaly 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);
};
答案 0 :(得分:2)
就在这里:
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);