javascript对象IE8上的循环
javascript对象IE8上的循环,javascript,arrays,internet-explorer,object,for-loop,Javascript,Arrays,Internet Explorer,Object,For Loop,data是一个Json数据数组 每个对象的结构是: var data = [ { id: 0, img: "image_src", width: 107, height: 80, shadowBoxLink: "....", th: { width: 107, height: 70, img: "src" } }, { id: 1, img: "image_src"
data
是一个Json数据数组
每个对象的结构是:
var data = [
{
id: 0,
img: "image_src",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 70,
img: "src"
}
},
{
id: 1,
img: "image_src",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 80,
img: "src"
}
}
];
当我尝试在循环中访问阵列时(仅在IE8、IE7中发生),使用:
我收到一条错误消息:“无法获取“height”的属性引用为null或未定义”
(我把这条信息翻译成法语:不可能的高度,不可能的高度)
我做错了什么?访问数组元素可以在语义上做得更好,如下所示:
for(var i = 0, n = data.length; i < n; i ++) {
var imgHeight = data[i].th.height;
...
}
看来你在找一个不存在的地方 做一个简单的测试:
for(var i in data) {
if(data[i] && data[i].th && data[i].th.height){
console.log('the property exists');
}else{
console.log("no, it doesn't")
}
}
有一个对象数组 因此,使用并获取所需对象的属性 给定代码中存在语法错误。用引号关闭字符串 示例代码在这里
var data = [
{
id: 0,
img: "image_src1",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 70,
img: "src"
}
},
{
id: 1,
img: "image_src2",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 40,
img: "src"
}
}
];
for(var i=0; i<data.length; i++) {
var imgHeight = data[i].th.height;
alert(imgHeight);
}
var数据=[
{
id:0,
img:“图像\u src1”,
宽度:107,
身高:80,
shadowBoxLink:“…”,
th:{
宽度:107,
身高:70,
img:“src”
}
},
{
id:1,
img:“图像\u src2”,
宽度:107,
身高:80,
shadowBoxLink:“…”,
th:{
宽度:107,
身高:40,
img:“src”
}
}
];
对于(var i=0;i@RobW问题中阐述的结构是数组中每个对象的结构(data
)例如,数据
是一个对象数组。Thx@Abody97,我刚刚忘记把它放在这里,但它存在于原始代码中。我尝试了您建议的循环,没有错误,但也没有显示任何内容。我正在试着调试它,看看是否有问题else@vladimire我认为这是其他地方的一个错误,因为我认为问题不在于对象本身,因为询问者说他只是在IE中得到了错误。你的方法是正确的,但这里的问题是不同的。请检查@Abody97的回答我尝试了你的方法,我得到了“属性存在”,除了最后一个!这就像数组中有一个空条目一样,是的@Abody97 answer说明了一切。由于您在
IE中使用的是for,因此IE不仅迭代数组内容,还迭代其他属性,而且它们当然没有th.height
。因此,请使用for()
loop,但我正在尝试访问th中的属性“height”?请参阅编辑以了解另一个可能的问题。
for(var i in data) {
if(data[i] && data[i].th && data[i].th.height){
console.log('the property exists');
}else{
console.log("no, it doesn't")
}
}
var data = [
{
id: 0,
img: "image_src1",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 70,
img: "src"
}
},
{
id: 1,
img: "image_src2",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 40,
img: "src"
}
}
];
for(var i=0; i<data.length; i++) {
var imgHeight = data[i].th.height;
alert(imgHeight);
}