2017-09-04 4 views
0

JavaScript에서 최소한 하나의 인수를 취할 "a"함수를 만들려고합니다.알 수없는 인수를 가져 오는 방법, 알 수없는 나머지 인수로 다른 함수를 호출하는 방법

이 함수는 첫 번째 인수를 추출한 다음 나머지 인수와 함께 다른 함수 "b"를 호출합니다. 이 같은

뭔가 : 나는 라인 작성하는 방법을 정말 확실 해요 그러나

var a = function() { 

    var name = arguments[0]; // get argument1  

    console.log("Running ", name); 

    b(<<argument2, argument3... to rest>>>); 
} 


var b = function() { 
    for (var i=0; i<arguments.length; i++){ 
     console.log(arguments[i]); 
    } 
} 

:

b(<<argument2, argument3... to rest>>>); 

은 "인수가"튀어 나올 수 따라서 배열로 변환 할 수 있습니다 첫 번째 인수. 그러나 나는 나머지 인수를 동적으로 b() 함수를 호출하는 방법을 정말 모르겠다.

JS에 b(arguments=myArr);과 같은 함수 호출이 있습니까?

대단히 감사합니다!

+1

당신이'.apply()'기능에 대해 알고, 및/또는 (['...'구문을 확산] 마 https://developer.mozilla.org/en/docs/Web/JavaScript/ 참조/운영자/Spread_operator)? – nnnnnn

+0

^이것에 대해 고마워, 지금 당장 배우십시오. – RyanN

답변

0

이보십시오.

var a = function() { 
    var name = arguments[0]; // get argument1 
    console.log("Running ", name); 
    var argsForB = Array.prototype.slice.call(arguments, 1); // converts arguments to an array and removes the first param 
    b.apply(null, argsForB); // calls b sending all the other params. Note that `this` inside b will be `null`. You can replace it with any other value. 
} 
var b = function() { 
    for (var i=0; i<arguments.length; i++) { 
    console.log(arguments[i]); 
    } 
} 
0

아마도 "a"함수에 배열을 전달하고 계획 한대로 첫 번째 값을 검색 한 다음 배열에 shift()을 사용하고 나머지 배열을 "b"함수에 전달합니다. 콘솔 로그에서

var a = function(arguments) { 
    var name = arguments[0]; // get argument1  
    console.log("Running ", name); 
    arguments.shift(); 
    b(arguments); 
} 

var b = function(arguments) { 
    for (var i=0; i<arguments.length; i++){ 
     console.log(arguments[i]); 
    } 
} 

a([1,2,3,4]); 

결과 :

Running 1 
2 
3 
4 
0
with ES6, you can use ... to extract array 

    var a = function() { 

     var name = arguments[0]; // get argument1  

     console.log("Running ", name); 
     var args = Array.prototype.slice.call(arguments); 
     args.shift() 
     b(...args); 
    } 


    var b = function() { 
     for (var i=0; i<arguments.length; i++){ 
      console.log(arguments[i]); 
     } 
    } 
+0

'arguments'는'.shift()'를 지원합니까? (그렇다면 왜'name = arguments.shift()'가되지 않습니까?) – nnnnnn

+1

ES2015 + 라우트를 사용한다면 왜 'var a = function (name, ... args) {b (... args); }' –

+0

emmm, Array.prototype.slice.call() – hailong

관련 문제