简体   繁体   中英

How do I select a JavaScript Object Array within an Object Method

How do I select the strings in the randomImage.images array from my randomImage.imagePicker method?

(function() {

var randomImage = {

        images : [
                'http://placehold.it/100x100',
                'http://placehold.it/200x200',
                'http://placehold.it/300x300',
                'http://placehold.it/400x400'
                ],//images Array
        imagePicker : function () {
                return console.log(randomImage.images[2]);
                }()//imagePicker Method

}//randomImage Object

})()

I get the following error in the console:

Uncaught TypeError: Cannot read property 'images' of undefined

Or if you want to specify the index of the randomImage you want to get:

imagePicker : function (idx) {
  return randomImage.images[idx];
}

randomImage.imagePicker(1) will return http://placehold.it/200x200

I get the following error in the console: Uncaught TypeError: Cannot read property 'images' of undefined

The problem is that you have () after the function definition:

imagePicker : function () {
    return console.log(randomImage.images[2]);
}()//imagePicker Method
 ^^

That will immediately call the function and assign its return value to imagePicker . But at this moment randomImage hasn't been initialized yet. Its value is still undefined and that's why you get that error.

Remove the parenthesis to assign the function itself (I assume that's what you want to do):

imagePicker : function () {
    return console.log(randomImage.images[2]);
}

Provided you just want it to return a random image from the images array:

DEMO

imagePicker : function () {
  var index = Math.floor(Math.random() * randomImage.images.length);
  return randomImage.images[index];
}

Returning just a specific image can be done using the index:

imagePicker : function () {
  // index 0 returns 'http://placehold.it/100x100'
  return randomImage.images[0];
}

this is the magic word:

    (function() {

    var randomImage = {

            images : [
                    'http://placehold.it/100x100',
                    'http://placehold.it/200x200',
                    'http://placehold.it/300x300',
                    'http://placehold.it/400x400'
                    ],//images Array
            imagePicker : function () {
                    alert(this.images[2]);
                    }//imagePicker Method

    }//randomImage Object

    randomImage.imagePicker();

 })();

Be aware that randomImage variable is not available outside of the auto-function!

Fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM