将数字数组映射到 JavaScript 中具有相应字符代码的对象
问题
我们需要编写一个接受数字数组的JavaScript函数。对于数组中的每个数字,我们需要创建一个对象。对象键将是数字,作为字符串。该值将是相应的字符代码,作为字符串。
我们最终应该返回一个结果对象的数组。
示例
以下是代码-
const arr = [67, 84, 98, 112, 56, 71, 82]; const mapToCharCodes = (arr = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const el = arr[i]; const obj = {}; obj[el] = String.fromCharCode(el); res.push(obj); }; return res; }; console.log(mapToCharCodes(arr));输出结果
以下是控制台输出-
[ { '67': 'C' }, { '84': 'T' }, { '98': 'b' }, { '112': 'p' }, { '56': '8' }, { '71': 'G' }, { '82': 'R' } ]