使用Titanium我想在单击下一个按钮后逐个循环遍历数组,然后使用前一个按钮向后循环

时间:2014-09-08 08:13:38

标签: javascript loops

//使用Titanium我想在点击下一个按钮之后逐个循环遍历一个数组,然后使用前一个按钮向后循环//但每次我这样做都会循环遍历整个数组...这就是我//到目前为止:

var fishArray = ["tang", "clownfish", "rabbit fish", "trigger fish", "blue green chromis", "angelfish"];
var index = 0;

var forwards = function(){

for(var i = index, j=fishArray.length; i<j; index++){
    var fishLabel = Ti.UI.createLabel({
        text: fishArray[index],
        backgroundColor: "#fff",
        width: 250,
        height: 200,
        top: view1.height + spacing,
        borderRadius: 5,
        borderWidth: 1
    });
    win1.add(fishLabel);
}
};


button1.addEventListener("click", backwards);
button2.addEventListener("click", forwards);

1 个答案:

答案 0 :(得分:0)

可能index++丢失了,你必须增加/减少它

并且循环看起来很奇怪

试试这个

for(var i = index; i<fishArray.length; i++)

并更改

text: fishArray[index],

text: fishArray[i],

整个代码:

var fishArray = ["tang", "clownfish", "rabbit fish", "trigger fish", "blue green chromis", "angelfish"];
var index = 0;

var labels = function(){
    for(var i = index; i<fishArray.length; i++){
        var fishLabel = Ti.UI.createLabel({
            text: fishArray[i],
            backgroundColor: "#fff",
            width: 250,
            height: 200,
            top: view1.height + spacing,
            borderRadius: 5,
            borderWidth: 1
        });
        win1.add(fishLabel);
    }
};
var backwards = function(){
    labels();
    index--;
};
var forwards = function(){
    labels();
    index++;
};


button1.addEventListener("click", backwards);
button2.addEventListener("click", forwards);