我有一个字符串数组,例如['2', '10', '11']
并想知道将其转换为整数数组的最有效方法是什么。我应该循环遍历所有元素并将其转换为整数还是有一个函数可以执行此操作?
Use map() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map and parseInt() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var res = ['2', '10', '11'].map(function(v) {
return parseInt(v, 10);
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
更简化的ES6箭头功能
var res = ['2', '10', '11'].map(v => parseInt(v, 10));
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
或者使用Number https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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 string
var res = ['2', '10', '11'].map(v => +v );
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
FYI : As @Reddy comment -
map() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map will not work in older browsers either you need to implement it (
Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.) https://stackoverflow.com/questions/2790001/fixing-javascript-array-functions-in-internet-explorer-indexof-foreach-etc ) or simply use for loop and update the array.
另外,它的文档中还有其他一些方法,请查看Polyfill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill,感谢@RayonDabre 的指出。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)