检查数组的所有值是否相等 [英] Check if all values of array are equal

查看:132
本文介绍了检查数组的所有值是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到所有值相等的数组。最快的方法是什么?我应该循环它并只比较值吗?

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] )   // true

Array.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.

这篇关于检查数组的所有值是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆