gpt4 book ai didi

javascript - 从头开始创建 .invoke()。为什么函数有效但方法返回未定义?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:46:25 27 4
gpt4 key购买 nike

我正在为一所基于 JavaScript 的编程学校做课前工作,但遇到了一个问题。这任务是从头重写一些 underscore.js 方法,这样我们就知道它们是如何工作的,而不是盲目地依赖它们。 我的 _.invoke 将传递函数引用而不是方法名称。

这是原始问题:

// Calls the method named by functionOrKey on each value in the list.
// Note: you will nead to learn a bit about .apply to complete this.

_.invoke = function(collection, functionOrKey, args) {
};

到目前为止,我的解决方案使用我之前编写的 _.map()(通过了自己的测试):

_.invoke = function(collection, functionOrKey, args) {
返回 _.map(集合,函数(值){
返回 functionOrKey.apply(value, args);
});
};

我的解决方案支持为functionOrKey传递一个函数。例如(来自 Mocha 测试套件):

var reverse = function(){
return this.split('').reverse().join('');
};

var reversedStrings = _.invoke(['dog', 'cat'], reverse);

reseversedStrings = "['god', tac']; //YAY!!

但是,在传递方法时,例如 toUpperCase,我收到错误消息:“TypeError:undefined is not a function”。任何建议表示赞赏!

编辑:找到失败的测试:

var upperCasedStrings = _.invoke(['dog', 'cat'], 'toUpperCase');

expect(upperCasedStrings).to.eql(['DOG', 'CAT']);

最佳答案

My solution would be:
_.invoke = function(collection, functionOrKey, args) {
//invoke when provided a method name
if(typeof functionOrKey === 'string'){
return _.map(collection, function(val){
return val[functionOrKey](args);
});
}
//invoke when provided a function reference
return _.map(collection, function(val){
return functionOrKey.apply(val, args);
});
};

关于javascript - 从头开始创建 .invoke()。为什么函数有效但方法返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24835704/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com