2017-02-10 1 views
2

간단한 배열 (배열)과 형식이 지정된 배열 (TypedArray)을 사용하는 응용 프로그램이 있습니다.모든 자바 스크립트 배열을 한 번에 확장

(min, max, sum, ...)과 같은 배열 유형에 필요한 확장을 몇 가지 개발했습니다.

하지만 여기 까다로운 부분이 있습니다. 자바 스크립트에서 모든 배열에 대해 만들어진 함수를 정의하는 방법은 무엇입니까?

모두 상속 계층이 있다면이 문제는 더 간단합니다. 그러나 지금까지 나는 더 이상 상위 클래스를 찾지 못했습니다. 지금은이 일을 해요 들어

:

// MIN FUNCTION 
Array    .prototype.min = 
Int8Array   .prototype.min = 
Int16Array   .prototype.min = 
Int32Array   .prototype.min = 
Uint8Array   .prototype.min = 
Uint16Array  .prototype.min = 
Uint32Array  .prototype.min = 
Uint8ClampedArray .prototype.min = 
Float32Array  .prototype.min = 
Float64Array  .prototype.min = function() { 
    // my code; 
} 

// MAX FUNCTION 
Array    .prototype.max = 
Int8Array   .prototype.max = 
Int16Array   .prototype.max = 
Int32Array   .prototype.max = 
Uint8Array   .prototype.max = 
Uint16Array  .prototype.max = 
Uint32Array  .prototype.max = 
Uint8ClampedArray .prototype.max = 
Float32Array  .prototype.max = 
Float64Array  .prototype.max = function() { 
    // my code; 
} 

// GO ON... 

이 내 눈을 찢어하려는 보면 너무 기괴 망측 추한입니다.

어떻게 향상시킬 수 있습니까? 이러한 모든 유형을 연결하여 사용할 수있는 것이 있습니까?

EDITED 질문 :
이 어떻게 명시 적으로 자바 스크립트 배열의 모든 유형을 작성하지 않고이 코드를 작성할 수 있습니다?

+0

TypedArrays는 프로토 타입을 공유하지 않는? _Also :'typed-array' 태그를 추가하는 것이 좋습니다. – evolutionxbox

+3

배열을 전달하는 함수를 사용하지 않는 이유는 무엇입니까? 예 : 'Math.max.apply (null, yourArrayOfTypeX); '를 실행하면 잘 작동합니다. – schroffl

+0

추가 할 메소드와 이름을 문자열로 받아 함수를 작성하고, 그 이름을 사용하여 각 프로토 타입에 메소드를 지정하는'prototype' 오브젝트를 반복합니다. –

답변

3

이 작동 할 나타납니다

function arMax(){ 
 
    var len = this.length; 
 
    var i; 
 
    var max=-Infinity; 
 
    for(i=0;i<len;i++) 
 
     if(this[i]>max) 
 
      max=this[i]; 
 
    return max; 
 
} 
 
function arMin(){ 
 
    var len = this.length; 
 
    var i; 
 
    var min=+Infinity; 
 
    for(i=0;i<len;i++) 
 
     if(this[i]<min) 
 
      min=this[i]; 
 
    return min; 
 
} 
 
for(tp of [ 
 
    Array, 
 
    Int8Array, 
 
    Int16Array, 
 
    Int32Array, 
 
    Uint8Array, 
 
    Uint16Array, 
 
    Uint32Array, 
 
    Uint8ClampedArray, 
 
    Float32Array, 
 
    Float64Array, 
 
]){ 
 
    tp.prototype.max = arMax; 
 
    tp.prototype.min = arMin; 
 
} 
 

 
console.log([ 2, 34, 3, 2, -43, -1 ].max()) 
 
console.log([ 2, 34, 3, 2, -43, -1 ].min())

+1

이것은 좋은 대답입니다 +1, 많이 향상 시키지만 '명시 적으로 모든 유형 작성'부분을 해결하지 못합니다. –

+0

@ JonnyPiazzi 그 중 몇 가지 유형 만 있습니다. 그 (것)들을 타자를 치기 위하여 큰 일이면 안된다. 당신은 일반적으로 모든 하위 레벨 (C, C++)에서 이런 종류의 일을합니다. Object.prototype에서 함수를 두드리는 것은 효과가 있지만, 너무 작다고 생각합니다. 나는 그것을 타이프하고 계속 나아 간다. (더 좋은 대답이 나오지 않는다면). – PSkocik

0

당신이 다음 창 개체 자체에서 사용할 배열의 목록을 얻을 수 있으며, 브라우저에서 우리이가는 경우.

var availableAr = []; 
 
Object.getOwnPropertyNames(window).forEach(function(name){ \t 
 
\t if(name.toString().indexOf('Array')!== -1){ 
 
     \t availableAr.push(name.toString()) 
 
    } 
 
}) 
 
console.log(availableAr); 
 
console.log( 
 
     new window[ availableAr[0] ]() 
 
);

관련 문제