版权声明:可任意转载,转载注明出处。 https://blog.csdn.net/Handsome_fan/article/details/82823987
操作数组的常见的方法有forEach
、map
、filter
,其中map
和filter
方法的返回值都是数组,forEach
的返回值是undefined
,可以理解为没有返回值。
由于原生的数组对象中,没有concatAll方法,所以打算自己实现一个。concatAll方法要做的事情很简单,就是把一个二维数组转成一维。
Array.prototype.concatAll = function() {
var result = [];
// 用 apply 完成
this.forEach((array) => {
result.push.apply(result, array);
});
return result;
};
这里我们用到了apply
方法。apply
方法会调用一个函数,apply
方法的第一个参数会作为被调用函数的this值,apply
方法的第二个参数(一个数组,或类数组的对象)会作为被调用对象的arguments值,也就是说该数组的各个元素将会依次成为被调用函数的各个参数。我们利用apply方法的这种特性,实现了数组的解构(降维)。
接下来,我们来解决一个问题:
var courseLists = [{
"name": "My Courses",
"courses": [{
"id": 511019,
"title": "React for Beginners",
"covers": [{
width: 150,
height: 200,
url: "http://placeimg.com/150/200/tech"
}, {
width: 200,
height: 200,
url: "http://placeimg.com/200/200/tech"
}, {
width: 300,
height: 200,
url: "http://placeimg.com/300/200/tech"
}],
"tags": [{
id: 1,
name: "JavaScript"
}],
"rating": 5
}, {
"id": 511020,
"title": "Front-End automat workflow",
"covers": [{
width: 150,
height: 200,
url: "http://placeimg.com/150/200/arch"
}, {
width: 200,
height: 200,
url: "http://placeimg.com/200/200/arch"
}, {
width: 300,
height: 200,
url: "http://placeimg.com/300/200/arch"
}],
"tags": [{
"id": 2,
"name": "gulp"
}, {
"id": 3,
"name": "webpack"
}],
"rating": 5
}]
}, {
"name": "New Release",
"courses": [{
"id": 511022,
"title": "Vue2 for Beginners",
"covers": [{
width: 150,
height: 200,
url: "http://placeimg.com/150/200/nature"
}, {
width: 200,
height: 200,
url: "http://placeimg.com/200/200/nature"
}, {
width: 300,
height: 200,
url: "http://placeimg.com/300/200/nature"
}],
"tags": [{
id: 1,
name: "JavaScript"
}],
"rating": 5
}, {
"id": 511023,
"title": "Angular2 for Beginners",
"covers": [{
width: 150,
height: 200,
url: "http://placeimg.com/150/200/people"
}, {
width: 200,
height: 200,
url: "http://placeimg.com/200/200/people"
}, {
width: 300,
height: 200,
url: "http://placeimg.com/300/200/people"
}],
"tags": [{
id: 1,
name: "JavaScript"
}],
"rating": 5
}]
}];
/*
var result = courseList
不得直接使用索引 covers[0],请用 concatAll, map, filter, forEach 完成
result 结果为 [
{
id: 511019,
title: "React for Beginners",
cover: "http://placeimg.com/150/200/tech"
}, {
id: 511020,
title: "Front-End automat workflow",
cover: "http://placeimg.com/150/200/arch"
}, {
id: 511022,
title: "Vue2 for Beginners",
cover: "http://placeimg.com/150/200/nature"
}, {
id: 511023,
title: "Angular2 for Beginners",
cover: "http://placeimg.com/150/200/people"
},
]
*/
这种类似的问题在我们实际的开发中是经常用到的,本人的答案如下:
var result = [];
var rel = courseLists.map((courseList) => {
return courseList.courses;
}).concatAll().forEach((courseListItem) => {
return result.push({
id: courseListItem.id,
title: courseListItem.title,
cover: (courseListItem.covers.filter((coversItem, idx) => {
if (idx === 0) {
return coversItem;
}
}))[0].url
})
});
console.log(result);