JS - for循环内部循环

时间:2017-03-30 07:38:37

标签: javascript jquery for-loop

我正在编写一个函数来计算数字,第一个循环从表行获取所有值,控制台返回:

apple is 0
banana is 1
orange is 2
watermelon is 3

如果有一个号码(例如:2)传递给该函数,则for循环将重新排列该号码,我希望控制台返回:

apple is 0
banana is 1
watermelon is 2

但控制台确实返回:

apple is 0
apple is 1
apple is 2
apple is 3
apple is 4
banana is 0
banana is 1
banana is 2
banana is 3
banana is 4
watermelon is 0
watermelon is 1
watermelon is 2
watermelon is 3
watermelon is 4

不知道如何修复它,这是我的代码

HTML部分:

<tr>
<td id="row_00">apple</td>
<td><a href="javascript:del_list(0);"><img src="delete.gif"></a></td>
</tr>
<tr>
<td id="row_01">banana</td>
<td><a href="javascript:del_list(1);"><img src="delete.gif"></a></td>
</tr>
<tr>
<td id="row_02">orange</td>
<td><a href="javascript:del_list(2);"><img src="delete.gif"></a></td>
</tr>
<tr>
<td id="row_03">watermelon</td>
<td><a href="javascript:del_list(3);"><img src="delete.gif"></a></td>
</tr>
<tr>
<td id="row_04"></td>
<td><a href="javascript:del_list(4);"><img src="delete.gif"></a></td>
</tr>

JS部分:

function del_list(number){
    //passing the number between 0 to 4
    for (i = 0; i < 5; i++) { 
        var list = $("#id" + i).val(); //table row from HTML
        console.log(list + " is " +i)

        if(i != number && list != ""){
            for (s = 0; s < 5; s++) {
                console.log(list + " is " +s)
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您不需要第二个for循环,使用一个循环并跳过{number}元素:

function del_list(number){
    //passing the number between 0 to 4
    for (var i = 0, index = 0; i < 5; i++) { 
        if (i != number) {
            var list = $("#id" + i).val(); //table row from HTML
            console.log(list + " is " + index++);
        }
    }
}