将字符串数组转换成整数数组不工作 [英] Converting string array into integer array not working

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

问题描述

我有以下数组:

s = "215, 216, 217" 

当我这样做

s.split(",").map(Number)

我得到这个回:

[NaN, 216, NaN] 

如果s只有两个数字,这两个回报为NaN。救命啊!

If s has only two numbers, both return as NaN. Help!

更新:

有它固定的!我已经摆脱引号包围字符串,因为我是从cookie中得到它的。

Got it fixed! I had to get rid of quotes that surrounded the string because I was getting it from a cookie.

s.replace(/\"/g, "").split(",").map(Number)

做的伎俩!

谢谢!

推荐答案

这将解释它:

s.split(",").map(function(item){ return item.trim() }).map(Number)

有号码之间的间距:

s = "215,/* here */ 216,/* here */ 217" 

其他可能的解决方案

s.replace(/\s/g,'').split(',').map(Number)

或什么,似乎是最初的方法,但使用普通防爆pression摆脱额外的空间:

or what it seems was the initial approach but using Regular Expression to get rid of the extra space:

s.split(/\s*,\s*/).map(Number)

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

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