讓我們假設我得到了一些數組的王...或者爲了簡單的鏈接。JS - 遍歷數組併爲if語句添加新數字
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煤泥答案是:
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!
}
}
有人下跌自由來糾正這個問題/答案,以便更好地說明問題。
仍然模糊!解釋更多! –
不要使用'link [i]',而是使用'link.push(item)'? – sweaver2112
創建一個計數器變量,並且只在「if」命中時增加它。請使用計數器變量而不是i – Aaron