[英]Altering array while iterating over
我有以下代碼:
for (let word in words) {
for (let i = 0; i < words.length; i++) {
// something
words.splice(i, 1);
i--;
}
}
而且我很傷心,即使我要更改接頭的尺寸,我仍如何繼續外部迭代。 我讀到我可以通過反向迭代來實現,但是這種解決方案僅適用於一個循環,而不適用於兩個循環。
謝謝。
如果要刪除元素,最好向后遍歷數組。
在我們的討論中,您需要將元素彼此比較,並且基於某些業務邏輯(在下面的代碼中隨機表示為10%)將拒絕提供的數組中的單詞。
JS
let words = ["one", "two", "three", "four", "five", "six"]; // 100.000 strings
for (let x = words.length - 1; x >= 0; x--) {
// if we're trying to access an element that no longer exists
if (typeof words[x] === 'undefined') continue;
for (let y = words.length - 1; y >= 0; y--) {
// if we're trying to access an element that no longer exists
if (typeof words[y] === 'undefined') continue;
// if word should be rejected
console.log('Comparing: ' + words[x] + ' ' + words[y]);
if (shouldRejectWordB(words[x], words[y])) {
// remove the word
console.log('Rejecting: ' + words[y]);
words.splice(y, 1);
}
}
}
console.log(JSON.stringify(words));
function shouldRejectWordB(wordA, wordB) {
// reject word randomly
if (Math.random() < 0.1) {
return true;
} else {
return false;
}
}
在進一步考慮這一點之后,遞歸函數似乎比上述函數更有效。 在上面的簡單continue
,遇到的undefined
索引處的任何元素。 因此,在處理過程中,我們仍在訪問n^2
元素。 另外,如果我們將當前單詞列表作為參數傳遞給遞歸函數,再與wordA
進行比較,則可以減少否定訪問已刪除單詞的嘗試,從而在刪除項目時加快后續迭代的速度。
JS
let words = ["one", "two", "three", "four", "five", "six"]; // 100.000 strings
function shouldRejectWordB(wordA, wordB) {
// reject word randomly
if (Math.random() < 0.1) {
return true;
} else {
return false;
}
}
function compareWordAToEachWord(wordA, words){
// loop through each provided word
for (let y = words.length - 1; y >= 0; y--) {
// if word should be rejected
console.log('Comparing: ' + wordA + ' ' + words[y]);
var wordToCompare = words[y];
if (shouldRejectWordB(wordA, wordToCompare)) {
// remove the word
console.log('Rejecting: ' + wordToCompare);
words.splice(y, 1);
// if we just rejected the word that is currently set as wordA stop comparing this loop
if(wordToCompare === wordA){
break;
}
}
}
if(words.length){
// the index of the current wordA
var index = words.indexOf(wordA);
// suggested index of the next word
var newIndex = words.length - 1;
console.log('index: '+index+' suggestion: '+newIndex);
// if the suggestion is the same or greater than the current word, get the item before the current word
if(index <= newIndex){
newIndex = index-1;
}
// if our suggestion is not for an element before the first (ie. invalid), begin another comparison
if(newIndex >= 0){
compareWordAToEachWord(words[newIndex], words);
}else{
// we have completed out looping through all words for comparison
console.log(JSON.stringify(words));
}
}
}
console.log(JSON.stringify(words));
// kick start the comparison with the last word in the list
compareWordAToEachWord(words[words.length - 1], words);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.