Function _ JavaScript tips for Retrieving Element indexes in javascript

Source: Internet
Author: User
I believe anyone who has used jQuery knows the index () method. It is very convenient for you to find the index location of the current element in the element set. How can you obtain it in native JavaScript? This is a problem I found in my article about writing structure/performance/behavior separation tabs (jQ and native JS. today, a friend asked me this question. This function is indeed very practical. I will share with you my implementation methods.
Code:

The Code is as follows:


Function index (current, obj ){
For (var I = 0; I <obj. length; I ++ ){
If (obj [I] = current ){
Return I;
}
}
}


Principle:
Find the elements in the current set that are equal to the current element through a for loop traversal. The lower value of this element is the index value of the current element in the element set.

Optimization:

The Code is as follows:


Function index (current, obj ){
For (var I = 0, length = obj. length; I If (obj [I] = current ){
Return I;
}
}
}

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.