typescript中,map用法
在 TypeScript 中,你可以使用 Array.prototype.map
方法来处理数组。这个方法会对数组中的每一项执行一个指定的函数,并返回一个新的数组,这个新数组的元素是原始数组元素经过函数处理后的结果。
下面是一个例子,假设我们有一个对象数组,我们想要将这个数组映射成一个只包含对象中某个属性值的数组:
interface ChartItem {
id: number;
chartname: string;
};
let chartList: ChartItem[] = [
{ id: 1, chartname: 'My Chart 1' },
{ id: 2, chartname: 'My Chart 2' },
// ... 更多项
];
let names = chartList.map(item => item.chartname);
console.log(names); // Output: ['My Chart 1', 'My Chart 2']
在这个代码中,map
函数接收一个回调函数作为参数。这个回调函数会被数组的每一个元素调用,并且该元素会作为参数传递给回调函数。然后,回调函数的返回值被收集起来并放入一个新的数组中,这就是 map
方法的返回值。