[javascript] 함수의 모든 인수를 해당 함수 내에서 단일 객체로 가져올 수 있습니까?

PHP에는 func_num_argsfunc_get_args이 있으며 JavaScript와 비슷한 것이 있습니까?



답변

사용하십시오 arguments. 배열처럼 액세스 할 수 있습니다. arguments.length인수 수에 사용하십시오 .


답변

인자배열과 같은 객체 (아닌 실제 배열). 기능 예 …

function testArguments () // <-- notice no arguments specified
{
    console.log(arguments); // outputs the arguments to the console
    var htmlOutput = "";
    for (var i=0; i < arguments.length; i++) {
        htmlOutput += '<li>' + arguments[i] + '</li>';
    }
    document.write('<ul>' + htmlOutput + '</ul>');
}

사용해보십시오 …

testArguments("This", "is", "a", "test");  // outputs ["This","is","a","test"]
testArguments(1,2,3,4,5,6,7,8,9);          // outputs [1,2,3,4,5,6,7,8,9]

전체 세부 사항 : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments


답변

ES6은 함수 인자가 다음과 같은 “…”표기법으로 지정된 구문을 허용합니다.

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]);
}


답변

arguments함수의 인수가 저장되는 개체입니다.

arguments 객체는 배열처럼 작동하고 배열됩니다. 기본적으로 배열에는 수행하는 메서드가 없습니다. 예를 들면 다음과 같습니다.

Array.forEach(callback[, thisArg]);

Array.map(callback[, thisArg])

Array.filter(callback[, thisArg]);

Array.slice(begin[, end])

Array.indexOf(searchElement[, fromIndex])

arguments객체를 실제 배열 로 변환하는 가장 좋은 방법 은 다음과 같습니다.

argumentsArray = [].slice.apply(arguments);

그러면 배열이됩니다.

재사용 가능 :

function ArgumentsToArray(args) {
    return [].slice.apply(args);
}

(function() {
   args = ArgumentsToArray(arguments);

   args.forEach(function(value) {
      console.log('value ===', value);
   });

})('name', 1, {}, 'two', 3)

결과:

> value === name
> value === 1
> value === Object {}
> value === two
>value === 3


답변

원하는 경우 배열로 변환 할 수도 있습니다. 배열 제네릭을 사용할 수있는 경우 :

var args = Array.slice(arguments)

그렇지 않으면:

var args = Array.prototype.slice.call(arguments);

에서 모질라 MDN :

JavaScript 엔진 (예 : V8)에서 최적화를 방해하므로 인수를 분리해서는 안됩니다.


답변

다른 많은 사람들이 지적했듯이 arguments함수에 전달 된 모든 인수를 포함합니다.

동일한 인수로 다른 함수를 호출하려면 apply

예:

var is_debug = true;
var debug = function() {
  if (is_debug) {
    console.log.apply(console, arguments);
  }
}

debug("message", "another argument")


답변

더 완벽한 예를 들어 Gunnar와 비슷한 대답 : 모든 것을 투명하게 반환 할 수도 있습니다.

function dumpArguments(...args) {
  for (var i = 0; i < args.length; i++)
    console.log(args[i]);
  return args;
}

dumpArguments("foo", "bar", true, 42, ["yes", "no"], { 'banana': true });

산출:

foo
bar
true
42
["yes","no"]
{"banana":true}

https://codepen.io/fnocke/pen/mmoxOr?editors=0010