简体   繁体   中英

what did I do wrong (javascript object) Uncaught TypeError: Cannot read property '0' of undefined

var map = {
    columns: 25,
    rows: 12,
    size: calculateElementSize(),
    elements: function(){
        var elements = [];
        for(i = 0; i < this.columns; i++){
            elements[i] = [];
            for(j = 0; j < this.rows; j++){
                elements[i][j] = {
                    x: 0,
                    y: 0,
                    type: "basicElement",
                    status: 1
                }
            }
        }
    return elements;
    }
}
console.log(map.elements[0][0].x);

I meant to do an array of objects inside map object, any ideas what I did wrong? Thanks in advance ;d

console.log(map.elements()[0][0].x); You declared elements as function, but you did not invoke it.

Elements is a function as such you can't read it as an array. If it returned (with an explicit return elements in the elements function) elements, map.elements()[0][0].x might return something but likely not what you want.

What do you exactly expect to do with this map object?

Apart from not having any code for calculateElementSize(), I could get the value for 0,0 using:

 var map = { columns: 25, rows: 12, //size: calculateElementSize(), elements: [], createElements: function(){ var xelements = []; for(i = 0; i < this.columns; i++){ xelements[i] = []; for(j = 0; j < this.rows; j++){ xelements[i][j] = { x: 0, y: 0, type: "basicElement", status: 1 } } } this.elements = xelements; }, getElement: function(c, r) { return this.elements[c][r]; } } map.createElements(); console.log(map.getElement(0,0));

The elements array is created by the createElements() function and the getElement() function gets the column/row item (assuming I have column and row the right way around)

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