最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert string array "[1,2,3]" to array of number in Javascript - Stack Overflow

programmeradmin34浏览0评论

I have been searching for a solution but I only found the convertion from ["1","2","3"] to [1,2,3], but my question is how to convert this: "[1,2,3]" to [1,2,3].

It might be clear for many of you but for me not.

I have been searching for a solution but I only found the convertion from ["1","2","3"] to [1,2,3], but my question is how to convert this: "[1,2,3]" to [1,2,3].

It might be clear for many of you but for me not.

Share Improve this question edited Jun 9, 2015 at 11:42 5511002233 5138 silver badges19 bronze badges asked Jun 9, 2015 at 10:00 karlihnoskarlihnos 4251 gold badge7 silver badges24 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 11

There are a few ways:

  • Using the already-mentioned: eval("[1,2,3]")
  • Using the already-mentioned: JSON.parse("[1,2,3]")
    You can visit https://github.com/koldev/JsonParser and get the oficial implementation for browsers that don't have this method, like IE7.
  • Using jQuery's JSON interpreter: $.parseJSON("[1,2,3]")
  • Using the function constructor: Function("return [1,2,3];")()
  • Using any constructor: []["filter"]["constructor"]("return [1,2,3]")() (Thanks to JSF*ck)

The safest option is to use the JSON package, either from jQuery or your browser's native one.

Remember that eval is evil! It allows to execute arbitrary code.
The same goes for the Function constructors, but with those you can add 'return' to it.
If you do eval("[1,2,3]; evil();"), the evil() function will execute, while Function("return [1,2,3]; evil();") will prevent the execution of evil().
This is not the perfect solution, since one can still do Function("return evil() || [1,2,3];"), and evil() will be executed. But, in this case, [1,2,3] is only returned if evil() returns a falsy value ("", null, 0, false, ...).

Use the JSON.parse("[1,2,3]");

working example http://jsfiddle.net/bcguevd2/

You could also parse it by yourself:

var s = '[1,2,3]';
var a = s.slice(1, -1).split(',').map(Number);
// .slice(1, -1) -> "1,2,3"
// .split(',')   -> ["1", "2", "3"]
// .map(Number)  -> [1, 2, 3]

Variation:

var a = (s.match(/-?\d+/g) || []).map(Number);
// .match(/-?\d+/g)     -> ["1", "2", "3"]
// '[]'.match(/-?\d+/g) -> null
// (null || [])         -> []

One solution is to use JSON.parse()

JSON.parse("[1,2,3]")

Also you can use eval() if the source is a trusted one(Don't use eval needlessly!) like

eval("[1,2,3]")

You can use eval with the following caveat Don't use eval needlessly!

var myArray = eval("[1,2,3]");
    Well, "[1,2,3]" is a String object.
    You need to deserialize it using JSON.parse().

    e.g: 
    var arr = "[1,2,3]"
    JSON.parse(arr)

    output will be >> [1,2,3]

Note: browser console don't detect JSON.parse() or JSON.stringify()
You have to do it in your code editor.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论