我一直在阅读 semilar 问题和答案,试图找到解决方案,我正在处理 map 并获取必须转换为数组的字符串...... 我得到一个作为变量提供给我的字符串,我可以将其作为字符串访问:
coords = '[42.46329472141537,21.46498522471254],[42.463191829327116,21.4654574564449],[42.463524249310545,21.465586246917347],[42.463642970305486,21.465092550106277]';
我需要这个变量是一个数组,我试过 JSON.parse 它抛出一个错误,我尝试映射(Number)未定义并且我试图拆分,它正在变形我的数组...... 因此,我需要数组采用这种格式:
var newCoords = Array(Array([42.46329472141537,21.46498522471254]),Array([42.463191829327116,21.4654574564449]),Array([42.463524249310545,21.465586246917347]),Array([42.463642970305486,21.465092550106277]));
每条建议都会有所帮助。
最佳答案
要使其可解析,您必须将数组包装在可解析对象(对象属性、另一个数组等)中;
要将字符串包装在另一个对象中,您可以利用 template literals :
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.
// Wrap arrays in another array to get a parsable object
const coords = '[42.46329472141537,21.46498522471254],[42.463191829327116,21.4654574564449],[42.463524249310545,21.465586246917347],[42.463642970305486,21.465092550106277]';
console.log(JSON.parse(`[${coords}]`));
关于Javascript字符串到多维数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58764149/