使用 JavaScript 从 2 个值和键数组构建 Map

javascriptweb developmentfront end technologyobject oriented programming

假设我们有两个数组 −

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'
}

相关文章