javascript - 有人可以解释一下这个删除数组中重复值的函数是如何工作的吗?

标签 javascript arrays

我一直在寻找一个 JavaScript 函数来删除数组中的重复值。 我发现了这个功能:

function removeDuplicateElement(arrayName)
{
    var newArray=new Array();
    label:for(var i=0; i<arrayName.length;i++ )
    {   
        for(var j=0; j<newArray.length;j++ )
        {
            if(newArray[j]==arrayName[i]) 
            continue label;
        }
        newArray[newArray.length] = arrayName[i];
    }
    return newArray;
}

这就是我所需要的。 有人能解释一下这个函数实际上是如何工作的以及“标签:”是什么吗? 我无法理解这段代码的逻辑,如果有人能给我解释那就太好了。 10倍

最佳答案

在 JavaScript 中,您可以指定 label: 作为在 continuebreak 语句中跳转到的位置。因此,当到达 Continue 时,迭代将返回到外部 for 循环,而不是其所在的内部循环(这将是 Continue 的默认行为)

基本上,这个函数的工作原理是创建一个新数组newArray(不修改旧数组)并循环原始数组中的每个元素。如果尚未找到,它将原始数组中的元素添加到 newArray 中。它通过在旧数组循环的每次迭代中循环并查找匹配值 arrayName[i]

来确定它是否已存在于 newArray
function removeDuplicateElement(arrayName)
{
    // Declares a new array to hold the deduped values
    var newArray=new Array();
    // Loops over the original array
    // label: here defines a point for the continue statement to target
    label:for(var i=0; i<arrayName.length;i++ )
    {   
        // Loops over the new array to see if the current value from the old array
        // already exists here
        for(var j=0; j<newArray.length;j++ )
        {
            // The new array already has the current loop val from the old array
            if(newArray[j]==arrayName[i]) 
            // So it returns to the outer loop taking no further action 
            // This advances the outer loop to its next iteration
            continue label;
        }
        // Otherwise, the current value is added to the new array
        newArray[newArray.length] = arrayName[i];
    }
    // The new deduped array is returned from the function
    return newArray;
}

有关此上下文中继续功能的更多信息,have a look at the MDN documentation .

关于javascript - 有人可以解释一下这个删除数组中重复值的函数是如何工作的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13517772/

相关文章:

javascript - 三.js从ObjLoader中操作一个对象

javascript - 将固定应用于内部 Div 会禁用溢出 :Hidden?

c++ - 移动数组以替换删除的元素

javascript - 如何将div转换为输入,然后将输入转换为div(onclick)

javascript - 首次加载时,Slick Slider Items 不可见

javascript - 如何读取赋值包含 && 和 || 的表达式在 qml 的 javascript 中?

javascript - 如何使用jsp、javascript、css以粗体或颜色显示表格数据

php - 如何使用 PHP 和简单的 HTML DOM 实现多个数组(+形成)

python - 如何在 Python 中包裹字符串或数组并对包裹的字符串或数组进行切片?

C++ - 参差不齐的 4d 数组