简体   繁体   中英

How to check if the elements of an array are identical in javascript (more than 2 elements)

I am trying to make sure that a phone# is not all identical characters, example 1111111111 The code I am using works but there has to be a cleaner way. I've tried loops but that only compares two consecutive characters at a time. This is what I am using now:

if (MainPhone.value != "")
            {               
                if ((MainPhone.value == 1111111111) || (MainPhone.value == 2222222222) || (MainPhone.value == 3333333333) || (MainPhone.value == 4444444444) || (MainPhone.value == 5555555555) || (MainPhone.value == 6666666666) || (MainPhone.value == 7777777777) || (MainPhone.value == 8888888888) || (MainPhone.value == 9999999999) || (MainPhone.value == 0000000000))
                {
                window.alert("Phone Number is Invalid");
                MainPhone.focus();
                return false;
                }
            }

I found this recommendation for someone else' question but could not get it to work.

var dup = MainPhone.value.split('');
if all(dup == dup(1))

I would try something like this:

var phone = '11111211';
var digits = phone.split('').sort();
var test = digits[0] == digits[digits.length - 1];

Simply sort the array and compare first and last element..

You can use a regular expression like this to check if all characters are the same:

^(.)\1*$

Example:

var phone = '11111111';

if (/^(.)\1*$/.test(phone)) {
  alert('All the same.');
}

Demo: http://jsfiddle.net/Guffa/3V5en/


Explanation of the regular expression:

^   = matches start of the string
(.) = captures one character
\1  = matches the first capture
*   = zero or more times
$   = matches end of the string

So, it captures the first character, and matches the rest of the characters if they are the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM