javascript - 将字符串中的坐标转换为 int 数组

标签 javascript

我是 javascript 初学者,在将字符串转换为 int 数组时遇到问题。 我发现这个案例

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

但不适用于这个:

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

并且具有相同的语法

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

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

最佳答案

试试这个:

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()

我不建议您使用eval()函数。

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.

关于javascript - 将字符串中的坐标转换为 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37005547/

相关文章:

JavaScript 无法解析为 Number

php - 如何: HTML table row click results in POST form linking to subsequent page

javascript - 异步加载 Deezer Javascript SDK

javascript - 错误 - 预期是赋值或函数调用,但看到的是表达式

javascript - 单击按钮时将焦点设置在滚动上

javascript - 遍历需要显示垂直列 3 年的数据,只显示包含数据的月份

javascript - 尝试附加一个元素 jQuery

javascript - 我如何使用纯 javascript 搜索 dom 以查找自定义链接属性?

javascript - 设置 chrome 应用的最小宽度

javascript - 我想清除 jQuery 存储的所有数据