Internet Explorer 브라우저 용 JavaScript에서 Array indexOf ()를 수정하는 방법
JavaScript를 오랫동안 사용 해본 적이 있다면 Internet Explorer가 Array.prototype.indexOf ()에 대한 ECMAScript 함수 (Internet Explorer 8 포함)를 구현하지 않는다는 것을 알고 있습니다. 다음 코드를 사용하여 페이지의 기능을 확장 할 수 있기 때문에 큰 문제는 아닙니다.
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
언제 구현해야합니까?
프로토 타입 함수가 존재하는지 여부를 확인하고 그렇지 않은 경우 어레이 프로토 타입을 확장하는 다음 확인으로 모든 페이지에 랩핑해야합니까?
if (!Array.prototype.indexOf) {
// Implement function here
}
또는 브라우저 확인을 수행하고 Internet Explorer 인 경우 구현합니까?
//Pseudo-code
if (browser == IE Style Browser) {
// Implement function here
}
이렇게하세요 ...
if (!Array.prototype.indexOf) {
}
일반적으로 브라우저 감지 코드는 크지 않습니다.
또는 jQuery 1.2 inArray 함수를 사용할 수 있으며 브라우저에서 작동합니다.
jQuery.inArray( value, array [, fromIndex ] )
전체 코드는 다음과 같습니다.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
정말 철저하게 대답 코드 이것뿐만 아니라 다른 배열 함수의 스택 오버플로 질문 체크 아웃 인터넷 익스플로러 (같이 IndexOf의 Foreach 등)에 자바 스크립트 배열 함수를 수정 .
underscore.js 라이브러리에는 대신 사용할 수 있는 indexOf 함수가 있습니다.
_.indexOf([1, 2, 3], 2)
를 사용하여 정의되어 있지 않은지 확인해야합니다 if (!Array.prototype.indexOf)
.
또한 구현 indexOf
이 올바르지 않습니다. 진술 ===
대신에 사용해야 ==
합니다 if (this[i] == obj)
. 그렇지 않으면 [4,"5"].indexOf(5)
구현에 따라 1이 잘못됩니다.
Mozilla 공식 솔루션이 있습니다 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
(function() {
/**Array*/
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (null === this || undefined === this) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
})();
누락 된 기능을 찾는 사람에게 이것을 권장합니다.
http://code.google.com/p/ddr-ecma5/
그것은 누락 된 ecma5 기능을 대부분의 오래된 브라우저에게 가져옵니다. :)
이것은 내 구현이었습니다. 기본적으로 이것을 페이지의 다른 스크립트보다 먼저 추가하십시오. 즉, Internet Explorer 8의 글로벌 솔루션에 대한 마스터에서 저는 또한 모든 프레임 워크에서 사용되는 트림 기능을 추가했습니다.
<!--[if lte IE 8]>
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) {
return i;
}
}
return -1;
};
}
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
};
</script>
<![endif]-->
그것은 나를 위해 작동합니다.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
Underscore.js로
var arr=['a','a1','b'] _.filter(arr, function(a){ return a.indexOf('a') > -1; })
'development' 카테고리의 다른 글
CSS3의 border-radius 속성과 border-collapse : collapse는 혼합되지 않습니다. (0) | 2020.03.17 |
---|---|
레일을위한 크론 작업 : 모범 사례? (0) | 2020.03.17 |
SQL Server에서 숫자, 부동 및 소수의 차이점 (0) | 2020.03.17 |
자바 스크립트 : location.href와 위치 설정 (0) | 2020.03.17 |
파이썬리스트는 요소가 삽입 된 순서대로 유지되도록 보장합니까? (0) | 2020.03.17 |