繁体   English   中英

遍历时更改数组

[英]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;
    }
}

JS菲德尔


效率更新

在进一步考虑这一点之后,递归函数似乎比上述函数更有效。 在上面的简单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.

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