js遍历问题?

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

慕哥6287543
浏览 507回答 1
1回答

慕神8447489

用for循环的话,需要在for外面定义一个变量作为标志位:const arr = [1, 2, 3, 5, 6, 6 , 7];let has = false;for(let i = 0; i < arr.length; i++) {&nbsp; &nbsp; if (arr.indexOf(arr[i]) !== i) {&nbsp; &nbsp; &nbsp; &nbsp; has = true;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }};if (has) {&nbsp; &nbsp; console.log('x');} else {&nbsp; &nbsp; 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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript