简体   繁体   中英

Js: multidimensional array literal declared: Add elements

I wanted to know if its possible to ad elements to an array which is declared as the following... Please check the add() function, I can't figure out how to solve this problem. Thanks

It's not necessary, but I'd appreciate if you give an explanation since of c++ point of view programmer.

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

So right here:

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';
};

You can't add to myArray[3] because myArray[3] is undefined. You need to assign an empty array to myArray[3] first:

    myArray [3] = [];
    myArray [3][0] = 'New1';
    myArray [3][1] = 'New2';
    myArray [3][2] = 'New3';

Or more generally, assuming the idea is to add to the end of your array, you could do something like:

 var idx = myArray.length;
 myArray[idx] = [];
 myArray[idx][0] = "New 1";
 // ...

Or even something like:

var newArray = ["New1", "New2", "New3"];
myArray.push(newArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM