请考虑以下代码:
var watchList = [
{
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
console.log(watchList.length);
const rating = watchList.map((function test (item) {
console.log(item);
return {
title: item["Title"],
rating: item["imdbRating"]
};
}));
console.log(JSON.stringify(rating));
MDN链接
在我的特定代码块中,只与map()
语法有关的几个问题。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
使用地图:
`const rating = watchList.map((function test (item) {}`
参考MDN JavaScript文档在这种情况下我是正确的:
1] test
是提供给map()
方法的callback参数的参数吗?它没有声明callback是一个可选参数,所以我对上面的MDN语法感到困惑,当传递没有名称的匿名函数时,控制台中没有错误。
2)item
是提供给currentValue
方法的map()
参数的参数,该参数是watchList数组中的每个元素?
正如您在MDN中看到的:
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
如写
var new_array = arr.map(function(item){.....})
in []中的值是可选的,最后是绑定“ this”]
尤其是如果您将使用箭头功能
var new_array = arr.map(item=>{})
您也可以创建一个函数
function test(item){.....}
并在回调中使用
var new_array = arr.map(test(item))