JS JavaScript Array retrieves the specified element index, determines whether the same, duplicates, and filters data

Source: Internet
Author: User
Tags javascript array

Recently, many JavaScript codes have been written, and many methods in array are insufficient. It may be used after you add it yourself. <Br/> <SCRIPT type = "text/JavaScript"> <br/> // locate the returned index.-1 is returned if no index exists. <br/> array. prototype. index = function (EL) {<br/> var I = 0; <br/> for (VAR I = 0, Len = This. length; I <Len; I ++) {<br/> If (El = This [I]) {<br/> return I; <br/>}< br/> return-1; <br/>}; </P> <p> // whether the same is true, different return values: false <br/> array. prototype. same = function () {<br/> If (this. length = 0) {<br/> return true; <br/>}< br/> VaR Temp = This. Join (''). replaceall (this [0]," "); <br/> If (temp! = "") {<Br/> return false; <br/>}else {<br/> return true <br/>}< br/> }; <br/> // replaceall function reference: http://blog.csdn.net/IBM_hoojo/archive/2010/06/17/5675096.aspx </P> <p> // determine whether duplicate data exists <br/> array. prototype. iterate = function () {<br/> var flag = false; <br/> for (VAR I = 0, Len = This. length; I <Len; I ++) {<br/> for (VAR J = 0; j <Len; j ++) {<br/> If (this [I] = This [J] & I! = J) {<br/> flag = true; <br/> break; <br/>}< br/> return flag; <br/>}; </P> <p> // input a callback and filter the Array Based on the callback function conditions. <br/> array. prototype. filter = function (callback) {<br/> var rs = []; <br/> for (VAR I = 0, length = This. length; I <length; I ++) {<br/> If (callback (this [I], I) {<br/> Rs. push (this [I]); <br/>}< br/> Return Rs; <br/>}; </P> <p> window. onload = function () {<br/> var ary = [1, 2, 3, 4, 6, 4, 5]; <br/> alert (ary. index (6); <br/> alert (ary. same (); <br/> alert (ary. iterate (); <br/> var A = ary. filter (function (n, I) {<br/> return n> 4; <br/>}); </P> <p> alert (. length + "-" + A [0]); <br/>}< br/> </SCRIPT>

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.