我一直在寻找一个 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:
作为在 continue
或 break
语句中跳转到的位置。因此,当到达 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/