简体   繁体   English

删除数组中每个字符串的引号-Javascript

[英]Removing quotes from each string in an array - Javascript

I've searched here: http://w3schools.com/jsref/default.asp but could not find any convenience method to perform this function. 我在这里搜索过: http : //w3schools.com/jsref/default.asp,但是找不到任何方便的方法来执行此功能。 If I have an array var arrayOfStrings = ["20","10","30","100"] , is there a quick way to remove all quotes (") from each string in this array without having to loop through? 如果我有一个数组var arrayOfStrings = ["20","10","30","100"] ,有没有一种快速的方法可以删除该数组中每个字符串的所有引号(“),而不必循环通过?

I essentially want to create this: var arrayOfNumbers = [20,10,30,100] 我本质上是想创建这个: var arrayOfNumbers = [20,10,30,100]

Thanks 谢谢

If you want number conversion, you can do it like this... 如果要进行数字转换,可以这样进行...

var arrayOfNumbers = arrayOfStrings.map(Number);

The .map() method creates a new array populated with the return value of the function you provide. .map()方法创建一个新数组,其中填充了您提供的函数的返回值。

Since the built-in Number function takes the first argument given and converts it to a primitive number, it's very usable as the callback for .map() . 由于内置的Number函数采用给定的第一个参数并将其转换为原始数字,因此它非常适合用作.map()的回调。 Note that it will interpret hexadecimal notation as a valid number. 请注意,它将十六进制表示法解释为有效数字。


Another built-in function that would accomplish the same thing as the callback is parseFloat . 可以完成与回调相同的功能的另一个内置函数是parseFloat

var arrayOfNumbers = arrayOfStrings.map(parseFloat)

The parseInt function however will not work since .map() also passes the current index of each member to the callback, and parseInt will try to use that number as the radix parameter. 但是parseInt函数将不起作用,因为.map()还将每个成员的当前索引传递给回调,并且parseInt将尝试使用该数字作为基数参数。



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

[
    20,
    10,
    30,
    100
]

You could try like this: 您可以这样尝试:

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

Have a look to the parseInt function . 看一下parseInt函数

For browsers that support JSON.parse : 对于支持JSON.parse的浏览器:

var arr = ["20","10","30","100"];
var newArr = JSON.parse("[" + arr.join() + "]");
console.log(typeof arr[0]);  //string
console.log(typeof newArr[0]);  //number

You do not need to do anything, the double quotes in JavaScript are identifiers that state that the data within them is a string. 您无需执行任何操作,JavaScript中的双引号是表明它们中的数据是字符串的标识符。 This means they are not part of the array or data itself. 这意味着它们不是数组或数据本身的一部分。

You can loop using a standard For loop. 您可以使用标准的For循环进行循环。

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

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