如何从“参数”中获取切片 [英] How to get a slice from "arguments"

查看:134
本文介绍了如何从“参数”中获取切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有你知道参数是一个特殊的对象,它包含传递给函数的所有参数。

All you know that arguments is a special object that holds all the arguments passed to the function.

只要它不是数组 - 你就不能使用像 arguments.slice(1)这样的东西。

And as long as it is not an array - you cannot use something like arguments.slice(1).

所以问题 - 如何从参数中除了第一个元素之外的所有内容

So the question - how to slice everything but first element from arguments?

UPD

好像没有办法将它转换为数组

seems like there is no way without converting it to an array with

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

如果有人发布了另一个解决方案,那将会很棒,如果没有 - 我会检查第一个上面的一行作为答案。

If someone posts another solution it would be great, if not - I'll check the first one with the line above as an answer.

推荐答案

实际上并不需要干预数组函数。

使用 rest参数语法 ... rest 更干净,更方便。

Using rest parameter syntax ...rest is cleaner and more convenient.

示例

function argumentTest(first, ...rest) {
  console.log("First arg:" + first);

  // loop through the rest of the parameters
    for(let arg of rest){
        console.log("- " + arg);
    }
}

// call your function with any number of arguments
argumentTest("first arg", "#2", "more arguments", "this is not an argument but a contradiction");

...休息

  • See the example Fiddle
  • See MDN Documentation page

这篇关于如何从“参数”中获取切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆