如何将数字解析为字符串以进行递增?我必须做两行声明吗?以下代码无效。
['a', 'b'].map((o,i)=>({myStr: ++i.toString()}))
忽略数组,它只是示例,我希望这个 [{myStr: "1"},{myStr:"2"}]
其中 i 是 map 的索引。
最佳答案
你必须包装++i
:(++i).toString();
const res = ['a', 'b'].map((o,i) => ({myStr: (++i).toString()} ));
console.log(res);
你也可以使用模板文字:
const res = ['a', 'b'].map((o,i) => ({myStr: `${++i}`} ));
console.log(res);
关于javascript从数字递增到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51224216/