함수의 모든 인수를 해당 함수 내에서 단일 개체로 가져올 수 있습니까?
PHP에는 와 이 있는데 JavaScript에도 비슷한 것이 있나요?
최신 Javascript 또는 Typescript의 경우:
class Foo {
reallyCoolMethodISwear(...args) { return args.length; }
}
function reallyCoolFunction(i, ...args) { return args[i]; }
const allHailTheLambda = (...args) => {
return args.constructor == Array;
};
const x = new Foo().reallyCoolMethodISwear(0, 1, 2, 3, 4);
const y = reallyCoolFunction(3, 0, 1, 2, 3, 4, 5, 6);
const z = allHailTheLambda(43110, "world");
console.log(x, y, z); // 5 3 true
고대 Javascript의 경우:
를 사용합니다. 어레이처럼 액세스할 수 있습니다.사용하다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
object는 함수 인수가 저장되는 곳입니다.
Arguments 객체는 어레이처럼 동작하며 기본적으로 어레이와 같은 메서드를 가지고 있지 않습니다.예를 들어 다음과 같습니다.
Array.forEach(callback[, thisArg]);
Array.map(callback[, thisArg])
Array.filter(callback[, thisArg]);
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);
Mozilla MDN에서:
JavaScript 엔진(V8)의 최적화를 방해하기 때문에 인수를 슬라이스하지 마십시오.
다른 많은 사람들이 지적했듯이arguments
에는 함수에 전달되는 모든 인수가 포함되어 있습니다.
같은 arg를 사용하여 다른 함수를 호출하려면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
ES6에서는 다음과 같은 작업을 수행할 수 있습니다.
function foo(...args)
{
let [a,b,...c] = args;
console.log(a,b,c);
}
foo(1, null,"x",true, undefined);
함수 선언 시 몇 개의 인수를 사용할 수 있는지 모르는 경우 파라미터 없이 함수를 선언할 수 있으며 함수 호출 시 전달되는 인수 배열에 따라 모든 변수에 액세스할 수 있습니다.
이것이 도움이 되기를 바랍니다.
function x(...args) {
console.log( {...[...args] } );
}
x({a:1,b:2}, 'test');
출력:
{ '0': { a: 1, b: 2 }, '1': 'test' }
이것이 도움이 되는 코드이길 바랍니다.
function lazyLoadIcons(){
for(let i = 0; i < arguments.length; i++) {
var elements = document.querySelectorAll(arguments[i]);
elements.forEach(function(item){
item.classList.add('loaded');
});
}
}
lazyLoadIcons('.simple-2col', '.ftr-blue-ad', '.btm-numb');
~ 라훌닭시
ES6에서는 다음을 사용합니다.Array.from
:
function foo()
{
foo.bar = Array.from(arguments);
foo.baz = foo.bar.join();
}
foo(1,2,3,4,5,6,7);
foo.bar // Array [1, 2, 3, 4, 5, 6, 7]
foo.baz // "1,2,3,4,5,6,7"
ES6 이외의 코드의 경우는, JSON.stringify 와 JSON.parse 를 사용합니다.
function foo()
{
foo.bar = JSON.stringify(arguments);
foo.baz = JSON.parse(foo.bar);
}
/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]
/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]
문자열화 대신 보존이 필요한 경우 내부 구조화 복제 알고리즘을 사용합니다.
DOM 노드가 통과된 경우 관련 없는 질문에서와 같이 XML Serializer를 사용합니다.
with (new XMLSerializer()) {serializeToString(document.documentElement) }
된 각 를 에러 할 수 .JSON.stringify
올바르게 동작합니다.
레퍼런스
언급URL : https://stackoverflow.com/questions/4633125/is-it-possible-to-get-all-arguments-of-a-function-as-single-object-inside-that-f
'programing' 카테고리의 다른 글
http://localhost:8000/broadcasting/auth 404(찾을 수 없음) (0) | 2023.01.31 |
---|---|
어디에 isset() 및 !empty()를 사용해야 합니까? (0) | 2023.01.31 |
php: 예외를 포착하고 실행을 계속할 수 있습니까? (0) | 2023.01.31 |
Java API는 왜 쇼트나 바이트 대신 int를 사용하는가? (0) | 2023.01.21 |
수천 개의 SELECT 쿼리 속도 향상 (0) | 2023.01.21 |