var adList = new Array();
adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/*
adList[0]["h3"] = 'Product title2';
adList[0]["button"]["link"] = '#link-url';
adList[0]["button"]["text"] = 'Buy now';
adList[0]["h3"] = 'asdfasdfasdf';
adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';
adList[1]["h3"] = 'Product title2';
adList[1]["button"]["link"] = '#link-url';
adList[1]["button"]["text"] = 'Buy now';
adList[1]["h3"] = 'asdfasdfasdf';
我遇到错误 adList[0] is undefined
,我不能像这样定义数组吗?在为它分配变量之前,是否必须将 adList[0]
指定为数组?
请您参考如下方法:
问题是您试图引用尚未分配值的 adList[0]
。因此,当您尝试访问 adList[0]['img']
的值时,会发生这种情况:
adList -> Array
adList[0] -> undefined
adList[0]["img"] -> Error, attempting to access property of undefined.
尝试使用数组和对象文字符号来定义它。
adList = [{
img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg',
h3: 'Product title 1',
button: {
text: 'Buy now',
url: '#link-url'
}
},
{
img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg',
h3: 'Product title 2',
button: {
text: 'Buy now',
url: '#link-url'
}
}];
或者您可以简单地分别定义 adList[0]
和 adList[1]
并使用您的旧代码:
var adList = new Array();
adList[0] = {};
adList[1] = {};
adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';
... etc etc