Hamet Gholizadeh
Hamet Gholizadeh

Reputation: 267

Can't return a property of object from a JavaScript function

I have a JavaScript function:

function test(arr, index) {
    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i].index);
    }
}

I call the function like this:

test(myArr, 'name')

But it returns undefined. When I use function directly, like this, it works:

for (var i = 0; i < myArr.length; i++) {
    console.log(myArr[i].name);
}

This is my array:

var myArr = [{name: "hamed"}, {name: "hamed1"}]

I don't think I should use single quotes when I call a function but without quotes it does not work either.

Upvotes: 3

Views: 253

Answers (1)

tcigrand
tcigrand

Reputation: 2397

When you want to access the property by a variable, use bracket notation. This will evaluate the variable and then find that in the object.

function test(arr, index) {
    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i][index]);
    }
}

Upvotes: 9

Related Questions