Skip to content Skip to sidebar Skip to footer

Javascript: Looping An Object With Typeerror Property Undefined

I have an array of object called xs that store name xs = [ {name: 'Peter'}, {name: 'Doe'}, {name: 'Parker'}, {name: 'John'} ]; and i have a function setEmptyStr th

Solution 1:

Use this:

xs = [
    {name: "Peter"},
    {name: "Doe"},
    {name: "Parker"},
    {name: "John"}
];

for (var i = 0; i < 5; i++) {
  console.log(setEmptyStr(xs[i] && xs[i].name));
}

functionsetEmptyStr(v) {
  if (typeof v !== 'undefined') {
    return v;
  } else {
    return'';
  }
}

Testing xs[i] first prevents an error from trying to access a property of undefined.

Solution 2:

No, there's no errors in your code, but it's unsafe to loop over an array with an index which is higher than its length, it will throw this kind of error.

In your code xs[4] will be undefined that's why you got this error:

UncaughtTypeError: Cannot read property 'name'ofundefined

So you just need to catch and avoid this error like this:

for (var i = 0; i < 5; i++) {
    if(xs[i])
        console.log(setEmptyStr(xs[i].name));
}

Solution 3:

No name is not undefined:

Uncaught TypeError: Cannot read property 'name' of undefined

So actually xs[i] is undefined. Your loop runs 5 times, but you only have 4 elems. You might use .length to be shure:

for(var i=0;i<xs.length;i++)

Solution 4:

Here,

for (var i = 0; i < 5; i++) {
    console.log(setEmptyStr(xs[i].name));
}

You are trying to send name of individual array element without checking whether its available or not. in your 5 th entry you dont have anything so it return undefined. because your array length is 4.

so check whether you have object before send like this,

if(xs[i]) {
  setEmptyStr(xs[i].name)
}

Post a Comment for "Javascript: Looping An Object With Typeerror Property Undefined"