Use of indexof and lastindeof

Source: Internet
Author: User

IndexOf () and lastIndexOf () are the two methods that return the position index: All receive two parameters, where the IndexOf () method is searched backwards from the beginning of the array (position 0), and the LastIndexOf () method looks forward from the end of the array ; Returns-1 if not found.

In order to be more clear and easy to understand, the array is intentionally added several repetitions of the number:

1. indexOf ();

1) var num=[1,1,4,4,5,4,1,3,2,1];

Index:0 1 2 3 4 5 6 7 8 9

Alert (Num.indexof (1)); If you write a parameter here, you look for ' 1 ' in the NUM array, and return to the position you first found, index 0;

alert (Num.indexof); Here, if it is two parameters, it is in the NUM array from the previous back and from the 2 position to start looking for ' 1 ', and return to the position of the first find, index 6;

2) The IndexOf () method is case sensitive!

var msg= ' Hello World ';

Alert (Msg.indexof (' h ')); The IndexOf method is case-sensitive, so this returns 1;

Alert (Msg.indexof (' World ')); Including the space inside, so the return is 6;

2.lastIndexOf ();

1) var num=[1,1,4,4,5,4,1,3,2,1];

Index:0 1 2 3 4 5 6 7 8 9

Alert (Num.lastindexof (1)); 9 If you write a parameter like indexof, return the position index value, the difference is that lastIndexOf () is looking forward from the back, but the index value is constant.

Alert (Num.lastindexof)//1 Here write two parameters, refers to the position from index 2 to start looking for ' 1 ', then you first find the number ' 1 ', is at the index value of 1 position.

It's important to note that browsers that support them include ie9+, Firefox, Safari, Opera 9.5+, and Chrome.

Use of indexof and lastindeof

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.