如何从 randomImage.imagePicker 方法中选择 randomImage.images 数组中的字符串?
(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
})()
我在控制台中收到以下错误:
Uncaught TypeError: Cannot read property 'images' of undefined
最佳答案
I get the following error in the console:
Uncaught TypeError: Cannot read property 'images' of undefined
问题是在函数定义之后有 ()
:
imagePicker : function () {
return console.log(randomImage.images[2]);
}()//imagePicker Method
^^
这将立即调用该函数并将其返回值分配给imagePicker
。但此时randomImage
还没有初始化。它的值仍然是未定义
,这就是您收到该错误的原因。
删除括号以分配函数本身(我认为这就是您想要做的):
imagePicker : function () {
return console.log(randomImage.images[2]);
}
关于javascript - 如何在对象方法中选择 JavaScript 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32999868/