JavaScript server-side advanced Programming (Array.indexof () and LastIndexOf () methods)

Source: Internet
Author: User

Syntax format:

Array.indexof (searchelement[, FromIndex]);

Array.lastindexof (searchelement[, FromIndex]);

function: Returns a specified meta The position of the first occurrence of the vegetarian value in the array. The method will retrieve the array from beginning to end to see if it contains elements searchelement fromindex - 1

note: lastindexof

for indexof method fromindex -1

for lastIndexOf Method FromIndex may also be a negative integer value. When a negative integer is expressed, the expression from the end of section |fromindex| elements to start searching forward.

Example:
var index = [5, 8, 44].indexof (8);  The default search starts at index 0, results index=>2[12, 5, 8, 44].indexof (130,1);  Search at index value 1, Output 3[12, 5, 8, 44].indexof (130,-1); Output -1["Hello", "Hello", "Hello", "Hello", "Hello"].lastindexof (' Hello ',-1); Output 4["Hello", "Hello", "Hello", "Hello", "Hello"].lastindexof (' Hello ', 0); Output -1["Hello", "Hello", "Hello", "Hello", "Hello"].lastindexof (' Hello ',-2); Output 3


indexof and Method uses congruent ( === searching for strings and numbers may be fine, but searching for objects and arrays can be problematic. The code snippet below gives a strong proof:

var arr = [    {"name":  "Zhang", "blog":  "Http://www.zhang.com"},     {"name":  "John", "blog":  "http://www.john.com"},    {" Name ":" John Doe "," blog ":" Http://www.lisi.com "}];var index=arr.indexof ({" Name ": " Zhang "," blog ": " http ://www.zhang.com "}); Console.log (" index:  ", index);   //output: index:  -1var o1={" Name " :  "Zhang", "blog":  "http://www.zhang.com"},   o2={"name": "John Doe", "blog": "/HTTP// Www.lisi.com "};var arr_2=[o1,o2];var index_2= arr_2.indexof (O2); Console.log (" index_2:  ", index_2);   //output: index:  1 //ex3var arr_3=[[1,2,3],[' one ', ' both ', ' three ']];var  a1=[1,2,3];var a2=[' One ', ' both ', ' three '];var index_3=arr_3.indexof (A1); Console.log ("Index_3:   ", index_3);   //output: Index:  -1 var arr_4=[a1,a2];var index_4=arr_4. IndexOf (A1); Console.log ("Index_4:&nbsP; ", index_4);   //output: index_4:  0 

the above section1An example outputs the result of-1, why? In fact, the problem is to determine whether two objects are equal. in the JSin development, when judging whether two objects are equal, only two objects point to the same address, and the two objects are equal, and sometimes two objects may have equal properties and values, but the two objects are still unequal. The same is true for two arrays (also objects) that are judged equal.

utility function findAll

A simple utility function is given below FindAll , based on indexOf that is used to find the subscript of all the matching elements in the array. This function returns an array of all the subscript elements.

function findall (arr,value) {    var results= [],len=arr.length,pos=0;     while (Pos<len) {         pos=arr.indexof (Value,pos);         if (pos===-1)  break ;         results.push (POS);         pos++;    }    return results;} Var indice=findall ([, 1,2,3,4,5,6,3,,5,7,89,3,2,3],3); Console.log (' indice:  ', indice);//Result: Indice: &NBSP;&NBSP;[&NBSP;3,&NBSP;7,&NBSP;12,&NBSP;14&NBSP;] Universal solution (for ECMASCRIPT3 and ECMASCRIPT5) 
 array.prototype.indexof = array.prototype.indexof | |  function  (Value, start)  {        if  (start  && typeof start !==  ' number ')  {             throw typeerror (start +  '  is not a  Number ');         }        var  start = start | |  0,            len = this.length;         if  (start > 0)  {             start = math.floor (start);         } else if  (start < 0)  {             start = math.ceil (start)  + len;         }        for  (var i = start; i  < len; i++)  {             if  (This[i] === value)  {                 return i;             }        }        return  -1;    };     Array.prototype.lastIndexOf =  array.prototype.lastindexof | |  function  (Value, start)  {        if  (start  && typeof start !==  ' number ')  {     &Nbsp;      throw typeerror (start +  '  is not a  number ');        }         var len = this.length,             start = start | |  len - 1;        if  (start > 0)   {            start = math.floor (start);         } else if  (start < 0)  {             start = math.ceil (start)  +  len;        }        for   (var i = start; i >= 0; i--)  {            if  (This[i] === value)  {                 return i;             }        }         return -1;    };

This article is from the "Green Peak" blog, please make sure to keep this source http://zhuxianzhong.blog.51cto.com/157061/1651751

JavaScript server-side advanced Programming (Array.indexof () and LastIndexOf () methods)

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.