Search code examples
javascriptobjectencapsulation

what does this syntax mean? anArray[source].src = sourceImg;


var source = 0;
var subtitue = 1;

function rollOver(sourceImg,  subImg) {

    var arrayImg = new Array;

    arrayImg[source] = new Image;
    arrayImg[source].src = sourceImg;
    arrayImg[subtitute] = new Image;
    arrayImg[subtitute].src = subImg;

    return arrayImg;
}

Solution

  • It means set the value of the object at anArray[source] to the value of sourceImg.

    Here arrayImg is an Array, which is normally represented as:

    var arrayImg = [];
    

    The source parameter is an index into that array, but because it's JavaScript, it doesn't actually need to be a number. This leads to confusion and/or issues, e.g., if source = 1000 you now have a 1000-entry array with a lot of undefined values, and it's pointless.

    This is fairly risky, and ultimately bad, code. It would be better expressed as an object, e.g.,

    function rollOver(srcImg,  subImg) {
      var img = new Image();
      img.src = srcImg;
    
      var sub = new Image();
      sub.src = subImg;
    
      return {
         main: img,
         sub:  sub
      };
    }
    

    (Noting that this is still heinous, and requires the code that's using the function to be fixed to not rely on position for values, because that's brittle.)

    Bottom line is that if this JS confuses you, SO is not the place to start, rather you should be looking at some basic JavaScript tutorials, and learn it right.