2014-04-24 2 views
9

메시지 유형을 정의하는 데 하나의 매개 변수를 사용하는 함수 message이 있습니다. 그런 다음 다른 인수를 결합하여 메시지를 구성합니다.인수 앞에 인수를 적용한 다음 적용하십시오.

그것은 다음과 같습니다

function message(type) { 
    var msg = _.rest(arguments).join(" "); 

    // Really the type will be used to set the class on a div 
    // But I'm just using console.log to keep it simple for now. 
    console.log(type + ": " + msg); 
} 

은 단순히 올바른 유형 message 전화 도우미 기능 error, warning, info을 제공하고자합니다. 이 문제를 해결하는 가장 좋은 방법은 확실하지 않습니다. 나는 두 가지 방법을 생각할 수 없다. 그러나 내가 올바르게 그것에 대해 가고 있는지, 아니면 아마도 내가 지나치게 복잡하게 만들고 있는지 확실하지 않다.

첫 번째 방법은 약간 중복 된 것처럼 보이며 첫 번째 arg와 인수를 포함하는 새로운 배열을 만든 다음이를 평평하게 만듭니다.

message.apply(this, _.flatten(["error", arguments])); 

두 번째 방법은 조금 어지럽습니까?

Array.prototype.unshift.call(arguments, "error"); 
message.apply(this, arguments); 

비록 내 실험실 기능에서 : 나는 다음과 같은 출력을 얻을

(function() { 
    Array.prototype.unshift.call(arguments, 0); 
    console,log(arguments); 
})(1, 2, 3); 

:

[0, 1, 2, 3, undefined, undefined, undefined, ..., undefined] 

답변

5

이보다 약간 더 효율적일 수 있습니다 참조 개 심자 먼저 실제 배열에 NG 다음 unshift :

var args = Array.prototype.concat.apply(["error"], arguments); 
message.apply(this, args); 

이 편집 : 입력 배열 병합 피하기 위해 더 나은 :

var args = ["error"]; 
args.push.apply(args, arguments); 
message.apply(this, args); 
+1

'arguments '요소가 배열 인 것처럼 요소 자체로 추가되는 대신 배열에'평평하게 '되는 것처럼주의하십시오. 예 : 'args = Array.prototype.concat.apply ([ "error"], [ "apple", "banana", [ "carrot", "cherry"]])'args = [ "error" "사과", "바나나", "당근", "체리"]'. – samthecodingman

관련 문제