将字符串转换为整数数组 [英] convert string into array of integers

查看:108
本文介绍了将字符串转换为整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下字符串 '14 2'转换为两个整数的数组。
我该怎么办?

I want to convert the following string '14 2' into an array of two integers. How can I do it ?

推荐答案

你可以 .split() 获取字符串数组,然后循环将它们转换为数字,如下所示:

You can .split() to get an array of strings, then loop through to convert them to numbers, like this:

var myArray = "14 2".split(" ");
for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; } 
//use myArray, it's an array of numbers

+ myArray [i] 只是一种快速进行数字转换的方法,如果您确定它们是整数,您可以这样做:

The +myArray[i] is just a quick way to do the number conversion, if you're sure they're integers you can just do:

for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); } 

这篇关于将字符串转换为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆