2

I'm beginner in javascript and I have a problem to convert a string to a array of int. I find for this case

var string = "[1,2,3,4]";

but not for this one:

var string = "[[1,2],[1,2]]";

And have the same syntax

var result = [[1,2],[1,2]];

result = [[1,2],[1,2]];
5
  • 3
    JSON.parse should handle both. Perhaps the question could be clearer. What is your expected output for var string = "[1,2,3,4]"; Commented May 3, 2016 at 13:29
  • I have a string : var string = "[[1,2],[1,2]]"; and I would this result : result = [[1,2],[1,2]]; Commented May 3, 2016 at 13:31
  • 2
    JSON.parse will convert that to the expected output. Commented May 3, 2016 at 13:32
  • otherwise use eval("[[1,2],[1,2]]") Commented May 3, 2016 at 13:33
  • 1
    Generally you should never use eval unless you have to dynamically write actual javascript code. Using it to parse JSON data is unsafe and highly discouraged. Commented May 3, 2016 at 13:34

1 Answer 1

2

Try this:

var 
  str = '[[1,2],[3,4]]',
  result;

result = JSON.parse(str);

result[0] // [1, 2]
result[1] // [3, 4]

result[0][0] // 1
result[1][1] // 4 

Read more about JSON.parse()

I don't recommend you to use eval() function.

Object-Oriented JavaScript - Second Edition: eval() can be useful sometimes, but should be avoided if there are other options. Most of the time there are alternatives, and in most cases the alternatives are more elegant and easier to write and maintain. "Eval is evil" is a mantra you can often hear from seasoned JavaScript programmers. The drawbacks of using eval() are:

Security – JavaScript is powerful, which also means it can cause damage. If you don't trust the source of the input you pass to eval(), just don't use it.

Performance – It's slower to evaluate "live" code than to have the code directly in the script.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.