0

This is a silly little question, I know, but I can't seem to find the answer to it...

I'm trying to change an image in Jquery using an array with the names, but it reads n, g and 2 instead of the actual values.

My code is:

var huidig = 1;
var arrayTekenen = jQuery.makeArray("peng1.png","peng2.png","peng3.png","peng4.png");

$(document).ready(
     function() {
         $('#next').bind('click', ClickNext);
     }
 )
 function ClickNext() {
    if(huidig<4)
       {
        huidig++; 
       }

    $("#tekenstap").attr('src', 'img/' + arrayTekenen[huidig]); 
 }

This is the error I get when clicking the object:

Failed to load resource (15:27:28:901 | error, network) at http:// localhost:8383/HTML5Application/img/n Failed to load resource (15:27:30:048 | error, network) at http:// localhost:8383/HTML5Application/img/g Failed to load resource (15:27:30:729 | error, network) at http:// localhost:8383/HTML5Application/img/2

Thanks in advance.

1
  • Oh, thanks, forgot that for a second there. Commented May 25, 2013 at 13:39

2 Answers 2

4

jQuery.makeArray doesn't do what you think it does.

It's not there to create an array. It transforms an array-like to a real array, and takes only one argument: the array-like.

If you want to create an array, use the following syntax:

var arrayTekenen = ["peng1.png","peng2.png","peng3.png","peng4.png"];

Some resource you should read: MDN Array.

Now you're asking me: what's an array-like object? It's an object that looks like an array, quacks like an array, walks like an array, but isn't an array. Examples are arguments, NodeLists or HTMLCollection. Mainly, they can be used as arrays, but don't have the array methods like slice, splice, forEach, etc.

What $.makeArray does is basically this:

function makeArray(obj) {
    return Array.prototype.slice.call(obj);
}

I leave it to you to understand how this works :-)

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

4 Comments

Thanks for the extra information. The amount of help I get from the people on this website is amazing.
You're welcome! This kind of comment is what makes it worthwile to contribute on this website :)
@FlorianMargaine +1, great answer and attitude.
@FlorianMargaine +1 You had me at quacks like an array. Great answer and explanation.
2

That is not how jQuery.makeArray works. Just use array literal notation:

var arrayTekenen = ["peng1.png","peng2.png","peng3.png","peng4.png"];

In your case, arrayTekenen turns out to be a string ("peng2.png") so arrayTekenen[i] is a character instead of the filename.

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.