我有一个包含这些值的数组:
var items = [Thursday,100,100,100,100,100,100]
我从 URL 查询字符串中获取这些值,因此它们都是字符串值。我希望除第一列之外的所有列都是数字。数组的列数可能会有所不同,所以有没有办法设置它,使 items[0] 始终是一个字符串,但 items[n] 始终是一个数字?
最佳答案
"...is there a way to set this so items[0] is always a string, but items[n] is always a number?"
使用.shift()
获取第一个,.map()
构建一个新的数字数组,然后使用.unshift()
> 将第一个添加回来。
var first = items.shift();
items = items.map(Number);
items.unshift(first);
演示: http://jsfiddle.net/EcuJu/
<小时/>我们可以像这样压缩它:
var first = items.shift();
(items = items.map(Number)).unshift(first);
<小时/>
关于javascript - 将数组值从字符串更改为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16548449/