从数组中的每个字符串中删除引号 - Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11782428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing quotes from each string in an array - Javascript
提问by Apollo
I've searched here: http://w3schools.com/jsref/default.aspbut could not find any convenience method to perform this function. 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?
我在这里搜索过:http: //w3schools.com/jsref/default.asp但找不到任何方便的方法来执行此功能。如果我有一个数组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
谢谢
回答by
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()
. Note that it will interpret hexadecimal notation as a valid number.
由于内置Number
函数接受给定的第一个参数并将其转换为原始数字,因此它非常适合用作.map()
. 请注意,它会将十六进制表示法解释为有效数字。
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 indexof each member to the callback, and parseInt
will try to use that number as the radixparameter.
parseInt
然而,该函数将无法工作,因为.map()
还将每个成员的当前索引传递给回调,parseInt
并将尝试使用该数字作为基数参数。
- MDN Array.prototype.map(includes compatibility patch)
- MDN Array.prototype.map (包括兼容性补丁)
DEMO:http://jsfiddle.net/UDWvH/
演示:http ://jsfiddle.net/UDWvH/
[
20,
10,
30,
100
]
回答by Bali Balo
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 函数。
回答by epascarello
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
回答by Disco Banana
You do not need to do anything, the double quotes in JavaScript are identifiers that state that the data within them is a string. This means they are not part of the array or data itself.
你不需要做任何事情,JavaScript 中的双引号是标识符,表明其中的数据是一个字符串。这意味着它们不是数组或数据本身的一部分。
You can loop using a standard For loop.
您可以使用标准 For 循环进行循环。