我在 js 中找到了获取唯一数组的脚本。当我在过滤函数下使用 if 条件时,返回的结果不正确,但是当我简单地返回数据时,结果是正确的。谁能解释一下为什么在 if 条件下检查结果是错误的?
var x= ["apple","orange","banana","apple","mango"];
//var y= x.indexOf('apple');
//alert(y);
function checkdup(x)
{
let uniquearr= x.filter(function(val,index,arr){
//return index== arr.indexOf(val); // return working correctly
if(arr.indexOf(val)==index)
{ return index; } // showing wrong result why
});
//return uniquearr;
console.log(uniquearr);
}
checkdup(x);
最佳答案
在决定是否将元素保留在返回的数组中时,filter
的返回值被转换为 true
或 false
。当你在做的时候
return index== arr.indexOf(val);
您正在返回一个 bool 值 - 您正在测试该元素是否是该元素在数组中的第一次出现。很好,这就是你想要的。但是当你
返回索引;
这总是为真,除非 index
为 0 - 这肯定没有达到您想要的效果。
关于javascript - 查询在javascript中查找唯一数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49595404/