本文介绍了检查数组的所有值是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到所有值相等的数组。最快的方法是什么?我应该循环它并只比较值吗?
I need to find arrays where all values are equal. What's the fastest way to do this? Should I loop through it and just compare values?
['a', 'a', 'a', 'a'] // true ['a', 'a', 'b', 'a'] // false推荐答案
const allEqual = arr => arr.every( v => v === arr[0] ) allEqual( [1,1,1,1] ) // true
或单行:
[1,1,1,1].every( (val, i, arr) => val === arr[0] ) // trueArray.prototype.every (来自MDN): every()方法测试数组中的所有元素是否都通过了测试由提供的函数实现。
Array.prototype.every (from MDN) : The every() method tests whether all elements in the array pass the test implemented by the provided function.
更多推荐
检查数组的所有值是否相等
发布评论