프로토타입 배열 객체 학습_prototype

WBOY
풀어 주다: 2016-05-16 18:49:44
원래의
878명이 탐색했습니다.
코드 복사 코드는 다음과 같습니다.

Array.from =

(function () {
//배열 프로토타입 참조
var arrayProto = Array.prototype,
slice = arrayProto.slice,
//JS 1.6에는 기본 forEach 메서드가 있습니다.
_each = arrayProto.forEach; // 사용 가능한 경우 기본 브라우저 JS 1.6 구현을 사용합니다.

function Each(iterator) {
for (var i = 0, length = this.length; i < length; i )
iterator(this[i]);
}
//JS1.6이 아닌 경우 _each는 객체의 각 메서드로 설정됩니다.
//여기서 _each 메서드는 _each in Enuerable Method
if (!_each) _each = Each;

functionclear() {
this.length = 0;
}

function first() {
return this[0];
}

function last() {
return this[this.length - 1]

//null이 아닌 배열의 모든 데이터 반환
function Compact() {
return this.select(function(value) {
return value != null;
}) ;
}

//다차원 배열을 1차원 배열로 변환
function flatten() {
return this.inject([], function(array, value) {
if (Object.isArray(value))
return array.concat(value.Flatten()); //여기에 재귀 호출이 있습니다.
array.push(value)
return array;
});
}

functionwith() {
var 값 ​​= Slice.call(arguments, 0)
return this.select(function( value) {
return !values.include( value);
});
}

function reverse(inline) {
return (inline !== false ? this: this.toArray())._reverse();
}

//배열에서 반복되지 않는 모든 요소를 ​​반환합니다. 배열이 정렬된 경우 true 매개변수를 전달하면 더 빠르게 실행됩니다.
function uniq(sorted) {
return this.inject([], function(array, value, index) {
if (0 == index || (sorted ? array.last() != value : ! array.include(value)))
array.push(value);
return array;
})
}

//두 배열의 교집합 구하기
function intersect(array) {
return this.uniq().findAll(function(item) {
return array.Detect(function(value) { return item === value });
} );
}


function clone() {
return Slice.call(this, 0)
}

function size() {
return this.length;
}

function inform() {
return '[' this.map(Object.inspect).join(', ') ']'; }

function toJSON( ) {
var results = [];
this.each(function(object) {
var value = Object.toJSON(object);
if (!Object.isUndefine(value)) results .push(value);
})
return '[' results.join(', ') ']'; >function indexOf(item, i) {
i || (i = 0);
var length = this.length
if (i < 0) i = length i; (; i < length; i )
if (this[i] === item) return i
return -1
}

function lastIndexOf(item, i) {
i = isNaN(i) ? this.length : (i < 0 ? this.length i : i) 1
var n = this.slice(0, i).reverse().indexOf (항목);
return (n < 0) ? n : i - n - 1
}

function concat() {
var array = Slice.call(this, 0), item;
for ( var i = 0, length =args.length; i < length; i ) {
item =args[i]
//두 번째 조건은 호출 메서드의 배열 요소도 연결되지 않습니다
if (Object.isArray(item) && !('callee' in item)) {
for (var j = 0, arrayLength = item.length; j < arrayLength; j )
array .push(item[j]);
} else {
array.push(item);
}
배열을 반환합니다.
}

/ Enumerable의 /mixin 메서드
Object.extend(arrayProto, Enumerable);

if (!arrayProto._reverse)
arrayProto._reverse = arrayProto. reverse;

Object.extend(arrayProto, {
_each: _each,
clear:clear,
first: first,
last: last,
compact: 컴팩트,
flatten: flatten,
없이: 없이,
reverse: reverse,
uniq: uniq,
intersect: intersect,
clone: ​​​​clone,
toArray: clone ,
size: size,
inspect :spect,
toJSON: toJSON
})

//온라인에서 이 버그를 발견하지 못했습니다. 그것?
var CONCAT_ARGUMENTS_BUGGY = (function() {
return [].concat(arguments)[0][0] !== 1;
})(1,2)

if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat;

//JS가 기본적으로 indexOf 및 lastIndexOf 메서드를 지원하는지 확인하세요. 그렇지 않은 경우
if (!arrayProto.indexOf) arrayProto 내의 메서드로 설정하세요. indexOf = indexOf
if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf
})();


지우기
복제
압축

첫 번째
평탄화

indexOf
검사
마지막
감소
역방향
size
toArray
toJSON
uniq
without
아래에는 간단한 메서드에 대한 예제가 제공되지 않습니다.
flatten():
코드 복사 코드는 다음과 같습니다.

[' Frank', ['bob', 'lisa'], ['jill', ['tom', 'sally']]].Flatten()
// -> ['frank', 'bob', 'lisa' , 'jill', 'tom', 'sally']


reduce(): 이 메서드의 의미는 숫자에 데이터가 있으면 이 데이터가 원본 배열
uniq():
코드 복사 코드는 다음과 같습니다. :

['샘', '저스틴', '앤드류', '댄', '샘'].uniq()
// -> Justin', 'Andrew', 'Dan']

['Prototype', 'prototype'].uniq()
// -> 비교는 대소문자를 구분합니다


without():
코드 복사 코드는 다음과 같습니다. 다음과 같습니다:

[3, 5, 6, 1, 20].without(3)
// -> [5, 6, 1, 20]

[3, 5, 6, 1, 20].없이( 20, 6)
// ->
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!