简体   繁体   English

JS-遍历数组并为if语句添加新的数字

[英]JS - iterating over array and add new numeric for if statement

Lets assume I got some king of array... or for simplicity links. 假设我有一些数组之王...或者为了简单起见。

HTML: 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: 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
    }
}

I hope everything is clear. 我希望一切都清楚。 I want to number link following from 1 [i+1] to the end without gaps. 我想对链接从1 [i + 1]到末尾的数字进行无间隙编号。

EDIT: I did try [y+1] before but thanks to @American Slime the answer is: 编辑:我之前尝试过[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!
        }
    }

anybody fell free to correct this question/answer to better describe the problem. 任何人都可以自由地纠正此问题/答案以更好地描述问题。

I'm pretty sure this is what you're asking... 我很确定这就是您要问的...

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++;

    };

};

I assume what you want is an array of myspecialPath links and another of other links. 我假设您想要的是myspecialPath链接数组和另一个其他链接。 You can use Array.prototype.push which doesn't care about the index like this: 您可以使用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]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM