简体   繁体   English

javascript从数字增加到字符串

[英]javascript increment from number to string

How can I parse number to string for increment? 如何将数字解析为字符串以进行增量? Do I have to make 2 line statement? 我必须做2行声明吗? Below code is not valid. 下面的代码无效。

['a', 'b'].map((o,i)=>({myStr: ++i.toString()}))

ignore the array, it's just sample, I expect this [{myStr: "1"},{myStr:"2"}] where i is the index of map. 忽略数组,它只是样本,我希望这[{myStr: "1"},{myStr:"2"}]其中i是地图的索引。

You have to wrap ++i : (++i).toString(); 你必须包装++i(++i).toString();

 const res = ['a', 'b'].map((o,i) => ({myStr: (++i).toString()} )); console.log(res); 

You can also use template literals: 您还可以使用模板文字:

  const res = ['a', 'b'].map((o,i) => ({myStr: `${++i}`} )); console.log(res); 

String构造函数中包装++i

['a', 'b'].map((o,i)=>({myStr: String(++i)}))
 var arr = ['a', 'b'];
 var newArr = arr.map((o,i)=>({myStr: (++i).toString()}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM