问题描述
我有一个像 ['2', '10', '11']
这样的字符串数组,我想知道将它转换为整数数组的最有效方法是什么.我应该循环遍历所有元素并将其转换为整数还是有执行此操作的函数?
使用 map()
和 parseInt()
var res = ['2', '10', '11'].map(function(v) {返回 parseInt(v, 10);});document.write('' + JSON.stringify(res, null, 3) + '')
更简化的 ES6 箭头函数
var res = ['2', '10', '11'].map(v => parseInt(v, 10));document.write('' + JSON.stringify(res, null, 3) + '')
或者使用Number
var res = ['2', '10', '11'].map(Number);document.write('' + JSON.stringify(res, null, 3) + '')
或者添加 +
符号将是解析字符串的更简单的想法
var res = ['2', '10', '11'].map(v => +v);document.write('' + JSON.stringify(res, null, 3) + '')
仅供参考:作为@Reddy 评论 - map()
将无法在旧浏览器中工作,或者您需要实现它(在 Internet Explorer 中修复 JavaScript 数组函数(indexOf、forEach 等) )或简单地使用 for 循环并更新数组.
还有一些其他方法存在于它的文档中,请查看 Polyfill ,感谢@RayonDabre 指出.
I have an array of strings like ['2', '10', '11']
and was wondering what's the most efficient way of converting it to an integer array. Should I just loop through all the elements and convert it to an integer or is there a function that does this?
Use map()
and parseInt()
var res = ['2', '10', '11'].map(function(v) {
return parseInt(v, 10);
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
More simplified ES6 arrow function
var res = ['2', '10', '11'].map(v => parseInt(v, 10));
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Or using Number
var res = ['2', '10', '11'].map(Number);
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Or adding
+
symbol will be much simpler idea which parse the stringvar res = ['2', '10', '11'].map(v => +v );
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
FYI : As @Reddy comment -
map()
will not work in older browsers either you need to implement it ( Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.) ) or simply use for loop and update the array.Also there is some other method which is present in it's documentation please look at Polyfill , thanks to @RayonDabre for pointing out.
这篇关于将字符串数组转换为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!