将字符串数字转换为数字数组

时间:2015-07-23 15:22:50

标签: javascript

ids_nn
["50348", "18646", "17963", "18184", "30703", "18016", "23225"]

我该如何制作:

[50348, 18646, 17963, 18184, 30703, 18016, 23225]

我读了这两篇SO帖子:

How to convert all elements in an array to integer in JavaScript?

convert string into array of integers

所以,我试过了:

var bla = ids_nn.map(function (x) { return parseInt(x, 10})
VM4765:2 Uncaught SyntaxError: Unexpected token }message: "Unexpected token }"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: ErrorVM3550:847 InjectedScript._evaluateOnVM3550:780 InjectedScript._evaluateAndWrapVM3550:646 InjectedScript.evaluate

var bla = ids_nn.split(',').map(Number)
VM4648:2 Uncaught TypeError: undefined is not a function

4 个答案:

答案 0 :(得分:0)

将其更改为

var bla = ids_nn.map(function (x) { return parseInt(x, 10)})
VM4765:2 Uncaught SyntaxError: Unexpected token }message: "Unexpected token }"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: ErrorVM3550:847 InjectedScript._evaluateOnVM3550:780 InjectedScript._evaluateAndWrapVM3550:646 InjectedScript.evaluate

答案 1 :(得分:0)

var bla = ids_nn.map(function (x) { return parseInt(x, 10})

如此接近 - 这就是你应该做的事情

var bla = ids_nn.map(function (x) { return parseInt(x, 10)})

一个)缺少

答案 2 :(得分:0)

这对我有用

var bla = ids_nn.map(function (x) { return parseInt(x) });

你和}和}有错,但无论如何你不需要通过基地

答案 3 :(得分:0)

你可以做到

var arrayOfNumbers = arrayOfStrings.map(Number);

对于不支持Array.map的旧浏览器,您可以使用Underscore

var arrayOfNumbers = _.map(arrayOfStrings, Number);