1

I have this array:

var arr = [
    ['First', 'lorem ipsum'],
    ['Second', 'dolor sit amet'],
];

and I want if arr[0] equals First do action 1, else do action 2.

I used:

for (var i = 0; i < markers.length; i++) {
    var arr = markers[i];
    var marker = new google.maps.Marker({
        map: map,
        if(arr[0] == 'Lorem') {
                icon: 'http://imgur.com/1.png',
                }
        else {
            icon: 'http://imgur.com/2.png',
            }
    });

    var contentString = '';

    google.maps.event.addListener(marker, "click", function () {
        infowindow.setContent(this.html);
        infowindow.open(map, this);
    });
}

but I get Uncaught SyntaxError: Unexpected token [.

How should I do this?

7
  • 1
    can you post you full code, it seems like the error is not related to the code you posted. Commented Dec 5, 2015 at 12:41
  • Please read How to Ask before asking questions Commented Dec 5, 2015 at 12:41
  • 1
    if(arr[0][0] == 'First') { Commented Dec 5, 2015 at 12:45
  • Sorry. I changed my code. Commented Dec 5, 2015 at 12:47
  • 1
    The posted code has several syntax errors. You can't use an if statement in an object literal. Commented Dec 5, 2015 at 12:49

1 Answer 1

1

You can't use an if statement in an object literal. The code has several syntax errors.

You can define a variable that refers to the object and conditionally add the property to it:

var obj = {
   map: map
};

if ( condition ) {
   obj.icon = 'http://imgur.com/1.png';
} else {
   obj.icon = 'http://imgur.com/2.png';
}

var marker = new google.maps.Marker(obj);

Another option is using a ternary operator:

var marker = new google.maps.Marker({
    map: map,
    icon: arr[0] == 'Lorem' ? 'http://imgur.com/1.png' : 'http://imgur.com/2.png'
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Is it possible with multiple if statements?
@wavix You are welcome. Yes, it is possible. I have updated the answer.

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.