AndrewLeonardi
AndrewLeonardi

Reputation: 3512

For Loop with Array is not working

I have a button that adds one word to the words variable. When the array is at certain lengths I want an image's src to change depending on the array length. Can't seem to get it to work.

var words = [];

var str = words;
for (var i = 0; i < str.length; i++) {
    if (str[i].length === 1) {
        img.src = "http://placehold.it/350x150"


        if (str[i].length === 2) {
            img.src = "http://placehold.it/200x150"

        }
    }
 }

Upvotes: 1

Views: 68

Answers (4)

Damon
Damon

Reputation: 4336

Assuming you want to dynamically change the image at certain breakpoints, you will also have to register a callback on your button to determine if an update is needed.

var words = [];

$(button).click(function() {
  words.push("whatever");
  var img = // get img here

  if (words.length === 1) {
    img.src = "http://placehold.it/350x150";
  } else if (words.length === 2) {
    img.src = "http://placehold.it/200x150";
  } 

  // etc
});

Edit: Here is a fiddle so you can see it working https://jsfiddle.net/4273v7c7/

Upvotes: 1

A. Campbell
A. Campbell

Reputation: 414

As Oriol commented, "Nesting if(str[i].length === 2) in if(str[i].length === 1)is useless."

It should be:

var words = [];

var str = words;
for (var i = 0; i < str.length; i++) {
    if (str[i].length === 1) {
        img.src = "http://placehold.it/350x150";
    }
    else if (str[i].length === 2) {
        img.src = "http://placehold.it/200x150";
    }
}

Upvotes: 0

Bekim Bacaj
Bekim Bacaj

Reputation: 5955

You don't need a loop for that.

var words = [];
var str = [0,"http://placehold.it/350x150", "http://placehold.it/200x150", ... ];
img.src = str[words.length] || img.src; 

This will do the job.

Upvotes: 0

Diego Polido Santana
Diego Polido Santana

Reputation: 1435

you are verifying the length of the position, you need to verify the array directly:

if (words.length === 1) {
  img.src = "http://placehold.it/350x150"
} else if (words.length === 2) {
  img.src = "http://placehold.it/200x150"
}

for that case you don't need a loop

Upvotes: 3

Related Questions