假设我们有两个数组-
const keys = [0, 4, 2, 3, 1]; const values = ["first", "second", "third", "fourth", "fifth"];
我们需要编写一个JavaScript函数,该函数接受键和values数组并将值映射到相应的键。输出应为-
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' }