3

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.

1
  • When you are doing arr[i].index, you are actually looking for property named index at ith index. Commented Jan 8, 2016 at 22:32

1 Answer 1

9

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]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.