假设我们有两个数组-
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' }