gpt4 book ai didi

javascript - js : multidimensional array literal declared: Add elements

转载 作者:行者123 更新时间:2023-12-02 14:26:04 25 4
gpt4 key购买 nike

我想知道是否可以将元素添加到声明如下的数组中...请检查 add() 函数,我不知道如何解决这个问题。谢谢

这不是必需的,但如果您从 C++ 程序员的 Angular 给出解释,我将不胜感激。

// 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);

关于javascript - js : multidimensional array literal declared: Add elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38231501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com