是否可以将函数的所有参数作为该函数内的单个对象获取?

发布于 2024-10-11 10:19:33 字数 259 浏览 6 评论 0原文

在 PHP 中,有 func_num_argsfunc_get_args,有类似的东西吗对于 JavaScript?

In PHP there is func_num_args and func_get_args, is there something similar for JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

末骤雨初歇 2024-10-18 10:19:34

希望这可能是有用的代码:

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');  

~ Rahul Daksh

Hope this could be the helpful code:

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');  

~ Rahul Daksh

蓝色星空 2024-10-18 10:19:34

在 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 节点,请像不相关的问题中一样使用 XMLSerializer。

with (new XMLSerializer()) {serializeToString(document.documentElement) }

如果作为小书签运行,您可能需要将每个结构化数据参数包装在 Error 构造函数中,以便 JSON.stringify 正常工作。

参考

In ES6, use 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"

For non-ES6 code, use JSON.stringify and 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]

If preservation is needed instead of stringification, use the internal structured cloning algorithm.

If DOM nodes are passed, use XMLSerializer as in an unrelated question.

with (new XMLSerializer()) {serializeToString(document.documentElement) }

If running as a bookmarklet, you may need to wrap the each structured data argument in an Error constructor for JSON.stringify to work properly.

References

画离情绘悲伤 2024-10-18 10:19:33

对于现代 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 作为参数数量。

For modern Javascript or 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

For ancient Javascript:

Use arguments. You can access it like an array. Use arguments.length for the number of arguments.

哎呦我呸! 2024-10-18 10:19:33

参数类似数组的对象(不是实际的数组)。示例函数...

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

The arguments is an array-like object (not an actual array). Example function...

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>');
}

Try it out...

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]

The full details: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

眼泪淡了忧伤 2024-10-18 10:19:33

ES6 允许使用“...”符号指定函数参数的构造,例如

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

ES6 allows a construct where a function argument is specified with a "..." notation such as

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]); 
}
情魔剑神 2024-10-18 10:19:33

arguments 对象是存储函数参数的地方。

参数对象的行为和外观都像一个数组,它基本上就是这样,它只是没有数组所具有的方法,例如:

Array.forEach(callback[, thisArg]);

Array.map(callback[, thisArg])

Array.filter(callback[, thisArg]);

Array.slice(begin[, end])

Array.indexOf(searchElement[, fromIndex])

的最佳方法如下:

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

我认为将 arguments 对象转换为 real数组

可重复使用:

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

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

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

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

结果:

> 值 === 名称
> 值 === 1
> 值===对象{}
> 值===二
> 值 === 3

The arguments object is where the functions arguments are stored.

The arguments object acts and looks like an array, it basically is, it just doesn't have the methods that arrays do, for example:

Array.forEach(callback[, thisArg]);

Array.map(callback[, thisArg])

Array.filter(callback[, thisArg]);

Array.slice(begin[, end])

Array.indexOf(searchElement[, fromIndex])

I think the best way to convert a arguments object to a real Array is like so:

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

That will make it an array;

reusable:

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

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

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

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

result:

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

苏佲洛 2024-10-18 10:19:33

如果您愿意,也可以将其转换为数组。如果数组泛型可用:

var args = Array.slice(arguments)

否则:

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

来自 Mozilla MDN:

您不应该对参数进行切片,因为它会阻止优化
JavaScript 引擎(例如 V8)。

You can also convert it to an array if you prefer. If Array generics are available:

var args = Array.slice(arguments)

Otherwise:

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

from Mozilla MDN:

You should not slice on arguments because it prevents optimizations in
JavaScript engines (V8 for example).

清眉祭 2024-10-18 10:19:33

正如许多其他人指出的那样,参数包含传递给函数的所有参数。

如果您想使用相同的参数调用另一个函数,请使用 apply

示例:

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

debug("message", "another argument")

As many other pointed out, arguments contains all the arguments passed to a function.

If you want to call another function with the same args, use apply

Example:

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

debug("message", "another argument")
究竟谁懂我的在乎 2024-10-18 10:19:33

与 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

Similar answer to Gunnar, with more complete example:
You can even transparently return the whole thing:

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 });

Output:

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

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

浪推晚风 2024-10-18 10:19:33

是的,如果您不知道在函数声明时可以有多少个参数,那么您可以声明不带参数的函数,并且可以通过在函数调用时传递的参数数组访问所有变量。

Yes if you have no idea that how many arguments are possible at the time of function declaration then you can declare the function with no parameters and can access all variables by arguments array which are passed at the time of function calling.

殤城〤 2024-10-18 10:19:33

在 ES6 中你可以这样做:

function foo(...args) 
{
   let [a,b,...c] = args;

   console.log(a,b,c);
}


foo(1, null,"x",true, undefined);

In ES6 you can do something like this:

function foo(...args) 
{
   let [a,b,...c] = args;

   console.log(a,b,c);
}


foo(1, null,"x",true, undefined);

月隐月明月朦胧 2024-10-18 10:19:33

希望这有帮助:

function x(...args) {
    console.log( {...[...args] } ); 
}

x({a:1,b:2}, 'test');

输出:

{ '0': { a: 1, b: 2 }, '1': 'test' }

Hope this helps:

function x(...args) {
    console.log( {...[...args] } ); 
}

x({a:1,b:2}, 'test');

Output:

{ '0': { a: 1, b: 2 }, '1': 'test' }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文