JavaScript中如何将带参数的函数作为参数传入另一个函数并调用
问题描述
我是一名JavaScript初学者,尝试编写如下代码:
function write(x, y, z) { x(); console.log("This is foo: ", y, z); } var b = 32, c = 92; function a(d) { console.log("This is d from a:", d); return d; } write(a(12), b, c);
运行后出现如下错误:
caspio-common.js:73 Uncaught TypeError: Cannot read properties of undefined (reading 'length') at HTMLDocument.<anonymous> (caspio-common.js:73:26) at f_dataPageReadyEvent.dispatchEvent (<anonymous>:1:523) at f_dataPageReadyEvent.init (<anonymous>:1:91) at new <anonymous> (<anonymous>:2:34) at <anonymous>:1:1 at f_dpLoadObj.addScriptElement (...
我的问题是:如何在write函数内部带参数调用x函数?
解决方案
你的代码核心逻辑存在问题:调用write(a(12), b, c)时,a(12)会立即执行并返回数字12,导致write函数里的x是数值而非函数,调用x()自然会引发错误(你当前的报错虽来自环境脚本,但逻辑错误必须修正)。
要在write内部带参数调用x,可按以下两种方式调整:
方式一:固定参数传递
将函数本身作为参数传入write,同时单独传递x所需的参数,在write内部调用时传入:
function write(x, xArg, y, z) { x(xArg); // 带参数调用x console.log("This is foo: ", y, z); } var b = 32, c = 92; function a(d) { console.log("This is d from a:", d); return d; } write(a, 12, b, c); // 传入函数a,而非a的执行结果
方式二:动态多参数传递
如果需要给x传递多个参数,可使用剩余参数语法提升灵活性:
function write(x, ...args) { // 拆分args:前两个给x,后两个作为y、z const [xArg1, xArg2, y, z] = args; x(xArg1, xArg2); console.log("This is foo: ", y, z); } var b = 32, c = 92; function a(d, e) { console.log("d from a:", d, "e from a:", e); return d + e; } write(a, 12, 24, b, c);
另外,你遇到的caspio-common.js报错属于运行环境自带脚本的问题,修正核心逻辑后可再验证是否还存在该错误。
内容的提问来源于stack exchange,提问作者Treadstone
相关产品推荐
相关产品推荐

