JavaScript 不支持 indexof 该如何解决_javascript技巧

WBOY
Release: 2016-05-16 15:07:26
Original
1424 people have browsed it

indexOf() 方法定义和用法

indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。

该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex 处或字符串的开头(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue 的第一次出现的位置。

stringObject 中的字符位置是从 0 开始的。

如果在数组中没找到字符串则返回 -1。

步入正题:

js中的 indexof方法查找给定元素能找在数组中找到的第一个索引值,但indexof在IE8下是不支持的,本文给大家介绍ie8 不支持 indexof 的解决方法

如何某浏览器不支持indexof,你可以在编写scripts时,在其开头使用以下代码,它能够允许你在没有本地支持的情况下使用indexOf方法。

if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; if (this == null) { throw new TypeError('"this" is 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; }; }
Copy after login

js不支持indexof的相关介绍就到此介绍完了,以上解决办法很管用,需要的朋友可以参考下以上教程,同时也非常感谢大家对脚本之家网站的支持!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!