我正在学习Javascript中的函数式编程,我在下面的代码中遇到了错误。该错误表明list
未定义。这显然来自我的filterVideos函数,因为它使用列表,但列表尚未定义。我知道我可以将函数放入我的return语句中,但我试图将函数与return语句分开。所以我的问题是,有没有办法在定义列表变量之前声明函数?
var myFunction = function() {
var lists = [
{
"id": 5434364,
"name": "New Releases"
},
{
"id": 65456475,
name: "Thrillers"
}
],
videos = [
{
"listId": 5434364,
"id": 65432445,
"title": "The Chamber"
},
{
"listId": 5434364,
"id": 675465,
"title": "Fracture"
},
{
"listId": 65456475,
"id": 70111470,
"title": "Die Hard"
},
{
"listId": 65456475,
"id": 654356453,
"title": "Bad Boys"
}
];
var filterVideos = function(video){ return video.listId == list.id;};
var mapVideos = function(video){return {id: video.id, title: video.title};};
return lists.map(function(list) {
return {
name: list.name,
videos: videos.filter(filterVideos).map(mapVideos)
};
});
}
myFunction();
答案 0 :(得分:2)
您可以更改filterVideos,以便生成具有范围列表的过滤功能:
var myFunction = function() {
var lists = [{
"id": 5434364,
"name": "New Releases"
}, {
"id": 65456475,
name: "Thrillers"
}],
videos = [{
"listId": 5434364,
"id": 65432445,
"title": "The Chamber"
}, {
"listId": 5434364,
"id": 675465,
"title": "Fracture"
}, {
"listId": 65456475,
"id": 70111470,
"title": "Die Hard"
}, {
"listId": 65456475,
"id": 654356453,
"title": "Bad Boys"
}];
var filterVideos = function(list) {
return function(video) {
return video.listId == list.id;
};
};
var mapVideos = function(video) {
return {
id: video.id,
title: video.title
};
};
return lists.map(function(list) {
return {
name: list.name,
videos: videos.filter(filterVideos(list)).map(mapVideos)
};
});
}
myFunction();
答案 1 :(得分:1)
正如您所说,错误是因为列表未在代码中的那一点定义。两个明显的解决方案是要么将其移动到定义它的范围(你说你不想做),要么将它作为参数传递给filterVideos函数,以便它可用内。
由于您无法更改过滤器传递给其回调的参数,因此最明显的解决方案是创建一个闭包,该闭包定义参数并返回一个具有" list"的函数。在范围内。
var filterVideos = function(list) {
return function(video) {
return video.listId == list.id;
}
};
var mapVideos = function(video){
return {id: video.id, title: video.title};
};
return lists.map(function(list) {
return {
name: list.name,
videos: videos.filter(filterVideos(list)).map(mapVideos)
};
});