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.
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.
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 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.
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).
There are a few ways:
eval("[1,2,3]")
JSON.parse("[1,2,3]")
$.parseJSON("[1,2,3]")
Function("return [1,2,3];")()
[]["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
, ...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With