我需要查找数组中是否存在不一样的值,存在的话执行函数x,不存在的话执行函数y。但是用for循环的话,开始如果遇到一样的会执行y,直到遇到不一样的才会执行x,如何让他全部遍历完在执行相应的函数?
1 回答

慕神8447489
TA贡献1780条经验 获得超1个赞
用for循环的话,需要在for外面定义一个变量作为标志位:
const arr = [1, 2, 3, 5, 6, 6 , 7];
let has = false;
for(let i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) !== i) {
has = true;
break;
}
};
if (has) {
console.log('x');
} else {
console.log('y');
}
如果支持ES6的话,可以用Set给数组去重,然后判断两个数组长度:
const arr = [1, 2, 3, 5, 6, 6, 7];
const arr1 = Array.from(new Set(arr));
console.log(arr.length === arr1.length);
添加回答
举报
0/150
提交
取消