如何创建一个接收一个参数的函数,并在控制台中打印该参数的基础值,无论是基本类型还是函数?
value = function(args){
return args.valueOf() //Only working for line 36
};
var scary = 'boo';
var first = function() { return 'bar'; };
var second = function() {
return first;
};
var third = function() {
return second;
};
var nested = function() {
return function() {
return function() {
return function() {
return function() {
return function() {
return function() {
return function() {
return function() {
return 'super nested';
};
};
};
};
};
};
};
};
};
// expected values for all these assessments
console.log(value(scary)); // should be 'boo'
console.log(value(first)); // should be 'bar'
console.log(value(second)); // should also be 'bar'
console.log(value(third)); // should also be 'bar'
console.log(value(nested)); // should be 'super nested'
Run Code Online (Sandbox Code Playgroud)
我在这里做的值函数只给了我第一行可怕而且只剩下其余的函数,我如何得到其他函数的值?
您可以检查args您收到的是否有.apply,如果是,则将您的value函数重用于您的参数结果
如果没有,则返回该值
var value = function(args){
if (args && args.apply) {
return value( args() );
}
return args;
};
var scary = 'boo';
var first = function() { return 'bar'; };
var second = function() {
return first;
};
var third = function() {
return second;
};
var nested = function() {
return function() {
return function() {
return function() {
return function() {
return function() {
return function() {
return function() {
return function() {
return 'super nested';
};
};
};
};
};
};
};
};
};
// expected values for all these assessments
console.log(value(scary)); // should be 'boo'
console.log(value(first)); // should be 'bar'
console.log(value(second)); // should also be 'bar'
console.log(value(third)); // should also be 'bar'
console.log(value(nested)); // should be 'super nested'Run Code Online (Sandbox Code Playgroud)
或者您可以使用类似于此处提到的方法来查看它是否是一个函数,我经常使用该.apply功能.
正如Ibu在评论中提到的,如果你需要这样的值函数,你可能需要检查你的代码设计.它可能会更加优化:)
| 归档时间: |
|
| 查看次数: |
51 次 |
| 最近记录: |