简体   繁体   中英

Can't access a object property of an array element, inside a object in javascript

I have an array of objects inside an object.

Why do I get the error 'Cannot read property fname of undefined' below? How do I fix it?

Also, I'm new to javascript and would appreciate any styling or convention suggestions.

https://jsfiddle.net/go1eu9z6/

function myObj() {
  this.X = [],

    this.haveEntries = function() {
      return this.A.length > 0;
    },

    this.add = function(fname_in, lname_in, city_in) {
      var t = new Date().getTime() / 1000;

      var obj = {
        fname: fname_in,
        lname: lname_in,
        city: city_in,
        t_create: t
      };

      this.X.push(obj);

      return this;
    }
}

var AB = {};
AB.X = new myObj();

AB.X.add("mike", 'smith', 'Toronto');

var s = AB.X[0].fname; // Error:  Cannot read property fname of undefined

document.getElementById('fname').innerHTML = s

There were a couple problems with your javascript code. Firstly, you were assigning AB.X a value of new Obj() instead of simply AB. Then, you were calling the add method on AB.X, when the correct call would simply be AB.add - see code example below

  function myObj() {
    this.X = [],

    this.haveEntries = function() {
      return this.A.length > 0;
    },

    this.add = function(fname_in, lname_in, city_in) {
      var t = new Date().getTime() / 1000;

      var obj = {
        fname: fname_in,
        lname: lname_in,
        city: city_in,
        t_create: t
      };

      this.X.push(obj);

      return this;
    }
}

var AB = {};
AB = new myObj();

AB.add("mike", 'smith', 'Toronto');

var s = AB.X[0].fname; 

You don't need to make X an instance of myObj. In fact, that's what's breaking your code. X is created when you make a new instance of myObject, like this:

var AB = new myObject();

Then you would be calling your add() method on this AB object, not on X:

AB.add('mike','smith','toronto');

Finally, you would get your results like this:

var firstName = AB.X[0].fname;

This is a little round-about why of constructing this object, though. How do you know which person's name and info occur at which index of X? Maybe look into using an object to store this data with some key that helps you know where stuff is. Might look like:

var people = {
    "uniqueID": {            // some uniqueID
       "fname":"mike",
       "lname":"smith",
       "city":"toronto"
    }
}

与您现有的代码,您也可以通过使用

var s = AB.X.X[0].fname;

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