JavaScript 中的地图采用键和值数组并映射值到对应键
假设我们有两个数组 −
const keys = [0, 4, 2, 3, 1]; const values = ["first", "second", "third", "fourth", "fifth"];
需要编写一个 JavaScript 函数,该函数采用键和值数组并映射值到对应键。
因此,输出应如下所示 −
const map = { 0 => 'first', 4 => 'second', 2 => 'third', 3 => 'fourth', 1 => 'fifth' };
因此,为该函数编写代码 −
示例
代码如下 −
const keys = [0, 4, 2, 3, 1]; const values = ["first", "second", "third", "fourth", "fifth"]; const buildMap = (keys, values) => { const map = new Map(); for(let i = 0; i < keys.length; i++){ map.set(keys[i], values[i]); }; return map; }; console.log(buildMap(keys, values));
输出
控制台中输出如下 −
Map(5) { 0 => 'first', 4 => 'second', 2 => 'third', 3 => 'fourth', 1 => 'fifth' }
广告