0

I'm a bit of a novice I was hoping someone could point out what I am doing wrong.

The idea is for searchArray to loop through array values &properties. It takes the arguments (property, value). When I call the function I get a RefernencError saying that property(hostname) is undefined. Is there something wrong with browsingHistory[i].property?

function searchArray(property, value) {
    for (i = 0; i < browsingHistory.length; i++) {
        return value === browsingHistory[i].property;
    }
}
2
  • What is browsingHistory? Is this another array ? Commented Apr 26, 2016 at 15:32
  • yes, browsingHistory is an array. it has objects in it with specific properties. Commented Apr 26, 2016 at 15:35

2 Answers 2

3

browsingHistory[i].property means the value of the property called "property".

use browsingHistory[i][property] instead


Demo

function searchArray(property, value) {
    for (i = 0; i < my_array.length; i++) {
        return value === my_array[i][property];
    }
}


var my_array = [
  {
    x: "foo",
    y: "bar"
  },
  {
    x: "foooooo",
    y: "baaaaar"
  }
]


// should output "true" because my array contains an element with a 
// property named "x" and which value is "foo"
document.body.innerHTML = searchArray("x","foo");

Sign up to request clarification or add additional context in comments.

4 Comments

I want it to point at the value of "property". basically I could check if the array has any objects with the host name : x
check my demo, is that what you are looking for ?
Thank you! I was doing basically the same thing but I was calling searchArray( x, foo) didn't realise I needed to put it in speechmarks. I am curious as to why though
because without quotes it is interpreted as an undeclared variable
0

If you using a variable as a property of any object, you can use with "." syntax.You have to use it as array with that property (like array indexes).For example

var property = "name";
....
anyObject[property] // equals to anyObject['name'] or anyObject.name

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.