JS 怎么把函数的参数(未知个数)传递给另一个函数?

2016-08-16 11:13:24 +08:00
 yuann72
function A(/*未知个数的参数*/){
console.log(/*传递给另一个函数*/);
}
A(1,2,3,4);
4306 次点击
所在节点    问与答
19 条回复
BuilderQiu
2016-08-16 11:19:37 +08:00
了解下: arguments
66beta
2016-08-16 11:21:49 +08:00
function aaa() {return bbb(arguments)}
function bbb(){console.log(arguments[0])}

aaa(1,2,3,4)
shyling
2016-08-16 11:22:01 +08:00
function got(...args){console.log(args)}
got(1,2,3,4)
tomato3
2016-08-16 11:24:58 +08:00
```
function A () {
console.log(arguments)
}
A(123,134,45)

```
morethansean
2016-08-16 11:27:47 +08:00
function A() {
B.apply(this, arguments);
}

function B() {
/** code here */
}

A(1,2,3,4,5);
yuann72
2016-08-16 11:30:43 +08:00
@tomato3
@66beta
这样写 输出的是 arguments 这个对象 // [1, 2, 3 , 4]
跟直接运行 console.log(1,2,3,4) 输出的不一样 // 1 2 3 4
yuann72
2016-08-16 11:36:38 +08:00
@morethansean 没看懂怎么用....
ETiV
2016-08-16 11:39:49 +08:00
查文档: arguments 、 apply

扩展: call 、 bind
Seita
2016-08-16 11:40:04 +08:00
你需要了解一下 Function.apply
plantain
2016-08-16 11:41:11 +08:00
function a(...p){b(...p)};
a(1,2,3)
airyland
2016-08-16 11:45:28 +08:00
楼上正解,但是要 babel 编译
dosin
2016-08-16 12:01:25 +08:00
5 楼说的优雅
yangg
2016-08-16 12:03:50 +08:00
var log = console.log.bind(console);
66beta
2016-08-16 12:05:00 +08:00
@yuann72 你到底要做什么功能呢?
console.log(1,2,3,4) 是打印四个参数
console.log([1,2,3,4])
yuann72
2016-08-16 12:41:26 +08:00
@66beta 我本来要的功能是把 console.log 改名为 其他
就是这个 我从其他地方得到的答案 :var log = console.log.bind(console)
不过我一楼描述错了,不过你们给的回复 我也可以用到其他地方
mdluo
2016-08-16 12:54:52 +08:00
典型的 X-Y Problem
finian
2016-08-16 13:01:35 +08:00
function A() { console.log.apply(console, [].slice.call(arguments)) }
ljbha007
2016-08-16 13:02:39 +08:00
5 楼正解
BOYPT
2016-08-16 13:27:00 +08:00
ES6 的话有新语法:
function fun1(...theArgs) {
console.log(theArgs);
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/299575

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX