简体   繁体   English

将数组值从字符串更改为数字

[英]Change array values to number from string

I have an array with these values: 我有这些值的数组:

var items = [Thursday,100,100,100,100,100,100]

I'm grabbing these from the URL query string so they are all string values. 我从URL查询字符串中获取它们,因此它们都是字符串值。 I want all columns except the first to be number. 我希望除第一列外的所有列均为数字。 The array may vary in the number of columns, so is there a way to set this so items[0] is always a string, but items[n] is always a number? 数组的列数可能有所不同,因此是否有一种方法可以设置此项,使得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?" “ ...是否有一种方法可以设置此项,使items [0]始终是字符串,而item [n]始终是数字?”

Use .shift() to get the first, .map() to build a new Array of Numbers, then .unshift() to add the first back in. 使用.shift()获取第一个, .map()构建一个新的数字数组,然后使用.unshift()添加第一个。

var first = items.shift();
items = items.map(Number);
items.unshift(first);

DEMO: http://jsfiddle.net/EcuJu/ 演示: http : //jsfiddle.net/EcuJu/


We can squeeze it down a bit like this: 我们可以这样压缩它:

var first = items.shift();
(items = items.map(Number)).unshift(first);

DEMO: http://jsfiddle.net/EcuJu/1/ 演示: http : //jsfiddle.net/EcuJu/1/


I think this should work for you. 我认为这应该为您工作。 You could set whatever default number you liked instead of 0. 您可以设置自己喜欢的默认数字,而不是0。

var items = ["Thursday","100","100","100","100","100","100"], i;
for (i = 1; i < items.length; i++)
{
    if(typeof items[i] !== "number")
    {
        items[i] = isNaN(parseInt(items[i], 10)) ? 0 : parseInt(items[i], 10);
    }
}

parseFloat() will convert your string to a number. parseFloat()会将您的字符串转换为数字。

Here is a sample code for modern browsers (won't work in IE7/IE8): 这是现代浏览器的示例代码(不适用于IE7 / IE8):

var convertedItems=items.map(function(element,index){
  // Convert array elements with index > 0
  return (index>0)?parseFloat(element):element;
});

There's also a parseInt() method for conversion to integers: 还有一个parseInt()方法可转换为整数:

parseInt(element,10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM