Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 278
kaka Avatar asked Jun 09 '15 10:06

kaka


People also ask

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you convert a string of numbers to an array of numbers?

You can convert a String to an integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.

How do I convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the unary plus operator ( + ) The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number.

What is array [- 1 in JavaScript?

As others said, In Javascript array[-1] is just a reference to a property of array (like length ) that is usually undefined (because it's not evaluated to any value).


1 Answers

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, ...).

like image 144
Ismael Miguel Avatar answered Oct 03 '22 08:10

Ismael Miguel