如何阻止我的阵列信息打印两次?

时间:2013-07-29 12:42:43

标签: javascript

我有一个对象数组

var event1Array {
    name: wedding;
    time: ["10:00am", "12:00pm"];
}
var event2Array {
    name: housewarming;
    time: ["7:00pm", "9:00pm"]
}

var eventArray = [event1Array, event2Array];

我想使用像这样的警告只使用两个循环(内部和外部)循环

alert("attend a " + eventArray.name + " starting " + theEvent.time) 

但我的活动信息会继续打印两次,如

attend a wedding starting 10am, 
attend a wedding starting 12pm
attend a housewarming starting 7pm
attend a housewarming starting 9pm

这是完整的代码

var event1Array 
{ 
    name: wedding; 
    time: ["10:00am", "12:00pm"]; 
}

var event2Array 
{ 
    name: housewarming; 
    time: ["7:00pm", "9:00pm"]; 
} 

var div = document.getElementById("events"); 
var eventArray = [event1Array, event2Array]; 

for (var i = 0; i < eventArray.length; i++) 
{
    var theEvent = eventArray[i];
    for (j = 0; j < theEvent.time.length; j++)
    { 
        console.log("Attending a wedding" + theEvent.name + "starting" + theEvent.time[j]); 
    }
}

2 个答案:

答案 0 :(得分:4)

它们不是阵列。 event1Arrayevent2Array实际上是Objects,因此您不希望循环使用它们。你应该只循环遍历eventArray

for (var i = 0,  len = eventArray.length; i < len; i++) {
    alert("attend a " + eventArray[i].name + " starting " + eventArray[i].time[0]);
}

这是一个有效的jsfiddle ...

答案 1 :(得分:0)

试试这个

alert("attend a " + eventArray.name + " starting " + theEvent.time[0])