Array.prototype.map():返回一个新数组,并在原始数组中的每个元素上调用提供的函数。
以下代码示例获取人员数组,并创建一个新数组,其中包含具有“ fullName”属性的人员
var personsArray = [
{
id: 1,
firstName: "Malcom",
lastName: "Reynolds"
}, {
id: 2,
firstName: "Kaylee",
lastName: "Frye"
}, {
id: 3,
firstName: "Jayne",
lastName: "Cobb"
}
];
// 返回由全名组成的新对象数组。
var reformatPersons = function(persons) {
return persons.map(function(person) {
// 创建一个新对象来存储全名。
var newObj = {};
newObj["fullName"] =person.firstName+ " " + person.lastName;
// 返回我们的新对象。
return newObj;
});
};现在reformatPersons(personsArray),我们可以呼叫并收到一个仅包含每个人全名的新数组。
var fullNameArray = reformatPersons(personsArray);
console.log(fullNameArray);
///输出
[
{ fullName: "Malcom Reynolds" },
{ fullName: "Kaylee Frye" },
{ fullName: "Jayne Cobb" }
]personsArray 其内容保持不变。
console.log(personsArray);
///输出
[
{
firstName: "Malcom",
id: 1,
lastName: "Reynolds"
}, {
firstName: "Kaylee",
id: 2,
lastName: "Frye"
}, {
firstName: "Jayne",
id: 3,
lastName: "Cobb"
}
]