How does javascript determine whether elements in an array are repeated? collection _ javascript skills

Source: Internet
Author: User
How does javascript judge whether the elements in the Array are repeated? var str = new Array ();
For example, there is an array with 20 18-digit ID card numbers.
Check whether the ID card number is repeated.
How to quickly determine?

The Code is as follows:


Var ary = new Array ("111", "22", "33", "111 ");
Var s = ary. join (",") + ",";
For (var I = 0; I {
If (s. replace (ary [I] + ",", ""). indexOf (ary [I] + ",")>-1)
{
Alert ("repeated! ");
}
}



The Code is as follows:


Var ary = new Array ("111", "22", "33", "111 ");
Var nary = ary. sort ();
For (var I = 0; I {If (nary [I] = nary [I + 1])
{Alert ("repeated content:" + nary [I]);}
}


Use the \ 1 in the regular expression (the first matching result)
First use join () to convert the array into a string and the separator \ x0f specified by the plug (this separator is generally not input). This step is purely for simplified and accurate scripts.
This mode is the trick I came up with when writing MzTreeView, and can skip the for loop to achieve extreme efficiency.

The Code is as follows:


Var hash = {};
For (var I in arr ){
If (hash [arr [I])
Return true;
Hash [arr [I] = true;
}
Return false;


<Script language = "JavaScript"> <! -- Function mm (a) {return/(\ x0f [^ \ x0f] +) \ x0f [\ s \ S] * \ 1 /. test ("\ x0f" +. join ("\ x0f \ x0f") + "\ x0f");} var ary = new Array ("111", "22", "33", "112 ", "22"); alert (mm (ary) // --> SCRIPT
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.