JS - 迭代数组并为if语句

时间:2017-03-01 15:50:56

标签: javascript iteration

让我们假设我有一些阵列之王......或者为了简单的链接。

HTML:

<a href'myspecialPath'></a>
<a href'myspecialPath'></a>
<a href'otherPath'></a>
<a href'otherPath'></a>
<a href'myspecialPath'></a>
<a href'myspecialPath'></a>

JS:

var test = document.getElementsByTagName('a');
var testLength = test.length;

for (i=0; i<testLength; i++){
    if (test.getAttribute('href').indexOf('myspecialPath') !== -1){
        //we list here every link with special patch
        // and I want it to have new numeration, not:
        link[i] have myspecialPath! // 1,2,5,6
        // cause it has gaps if link don't have special path - 1,2,5,6
        // and I want it to have numeric like 1,2,3,4
    }
else{
        link[i] without myspecialPath! // 3,4... and I want 1,2
    }
}

我希望一切都清楚。我想将1 [i + 1]之后的链接编号到没有间隙的结尾。

修改 我之前尝试过[y + 1],但感谢@American Slime答案是:

y = 0;
for (i=0; i<testLength; i++){
        if (test.getAttribute('href').indexOf('myspecialPath') !== -1){
            links:[y ++] have myspecialPath! // 1,2,3,4... and so on, OK - it's working fine!
        }
    }

任何人都可以自由地纠正这个问题/答案以更好地描述问题。

2 个答案:

答案 0 :(得分:1)

我很确定这就是你要问的......

var links = document.querySelectorAll('a');
var count = 1;

for (var i = 0; i <= links.length-1; i++) {

    if (links[i].getAttribute('href') === 'myspecialPath') {

        links[i].setAttribute('href', 'myspecialPath' + count);
        count++;

    };

};

答案 1 :(得分:1)

我假设你想要的是一组myspecialPath链接和另一个其他链接。您可以使用不关心索引的Array.prototype.push,如下所示:

var test = document.getElementsByTagName('a');
var testLength = test.length;

var specialLinks = [];
var otherLinks = [];

for (i=0; i<testLength; i++){
    // it should be test[i] not test
    if (test[i].indexOf('myspecialPath') !== -1){
        specialLinks.push(test[i]);
    }
    else{
        otherLinks.push(test[i]);
    }
}