2015-04-24 55 views
1

我正在尝试重新实现申请练习。我想出了一个天真的解决方案,在对象上下文中执行函数,方法是临时修饰该对象上的该函数,然后删除该函数。但我无法弄清楚当我调用它时,如何传递fn逗号分隔的参数,因为它们是数组形式。将数组转换为逗号分隔变量无需应用

如何将数组转换为逗号分隔的变量而不应用,调用或绑定?

function apply(fn, context, args) { 
    context.fn = fn; 
    var result = context.fn(); 
    delete context.fn; 
    return result; 
} 

function add(a,b) { 
    return a + b + this.num; 
} 

console.log(apply(add, {num: 10}, [3, 4])); //17 

编辑:

我不希望我的价值观分裂成一个字符串。我想我的价值分成comma separated form。这实际上是apply在通过数组时所做的。

+0

使用加入? 'join(',')'或者我真的误解了这个问题? – forgivenson

+0

对不起,这里有一个沟通不畅。我不想要一个字符串。我希望我的值用逗号分隔符来分隔https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator –

+0

嗯,你没有说不要使用'eval' ,所以你可以在'join'生成的字符串上使用'eval',但这是最好的避免。但是,您的用例听起来像是一种特殊情况,因为您正在重新创建内置函数。 – forgivenson

回答

1

尝试以下操作:

[1,2,3,4,5].join(",")

+0

嘿,我想我没有正确地传达我的问题。我刚刚更新了我的问题 –

1

您可以ES6与spread operator的帮助,这样做:

console.log(...myArray);

在写这篇文章的时候,这个功能支持通过FF37和诸如TraceurBabel的转译器。

这样做的另一种方法是由currying the function和循环传递参数。沿着线的东西:

myArray.forEach(curriedConsoleLog);

这么说,我看不出危害在仅仅使用apply

0

由于你的函数只能接受两个参数这会工作:

function apply(fn, context, args) { 
    context.fn = fn; 
    var result = context.fn(args[0],args[1]); 
    delete context.fn; 
    return result; 
} 

function add(a,b) { 
    return a + b + this.num; 
} 

console.log(apply(add, {num: 10}, [3, 4])); 
+0

这仅仅是一个示例来演示预期的输入和输出。我需要更全面的解决方案。 –

0
function apply(fn, context, args) { 
    context.fn = fn; 
    while (args.length) { 
     context.fn = context.fn(args.shift()); 
    } 
    return context.fn; 
} 

function cubus(a) { 
    return function (b) { 
     return function (c) { 
      return a * b * c/this.num; 
     } 
    } 
} 

function add(a) { 
    return function (b) { 
     return a + b + this.num; 
    } 
} 

document.write(apply(add, { num: 10 }, [3, 4])); 
document.write('<br>'); 
document.write(apply(cubus, { num: 10 }, [3, 4, 5])); 

看看What is 'Currying'?

相关问题