JavaScript does not support indexof how to solve _javascript skills

Source: Internet
Author: User
Tags abs

IndexOf () method definition and usage

The IndexOf () method returns the location of the first occurrence of a specified string value in a string.

This method retrieves the string stringobject from beginning to end to see if it contains substring searchvalue. The location at which to start retrieving is at the fromindex of the string or at the beginning of the string (no fromindex is specified). If a searchvalue is found, it returns the position of the first occurrence of searchvalue.

The character position in the Stringobject is starting at 0.

Returns-1 if no string is found in the array.

Step into the business:

IndexOf method in JS find the given element can find the first index value found in the array, but IndexOf is not supported under IE8, this article to introduce IE8 does not support indexof solution

How a browser does not support indexof, you can use the following code at the beginning of writing scripts, which allows you to use the IndexOf method without local support.

if (! Array.prototype.indexOf) {
Array.prototype.indexOf = function (Searchelement, fromindex) {
var k;
if (this = = null) {
throw new TypeError (' "This" was null or not defined ');
}
var O = Object (this);
var len = o.length >>> 0;
if (len = = 0) {
return-1
}
var n = +fromindex | | 0;
if (Math.Abs (n) = = Infinity) {
n = 0;
}
if (n >= len) {
return-1
}
K = Math.max (n >= 0 n:len-math.abs (n), 0);
while (K < len) {
if (k in O && o[k] = = searchelement) {return
k;
}
k++;
}
return-1;}

JS does not support the introduction of IndexOf to this introduction finished, the above solution is very useful, the need for friends can refer to the above tutorial, but also thank you very much for the cloud Habitat Community website support!

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.