javascript 将字符串转换为多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13630014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:19:54  来源:igfitidea点击:

Convert string to a multidimensional array

javascriptmultidimensional-array

提问by Fred

I have a string

我有一个字符串

 var myString = "['Item', 'Count'],['iPad',2],['Android',1]";

I need to convert it into an array where:

我需要将它转换成一个数组,其中:

myArray[0][0] = 'Item';
myArray[0][1] = 'Count';
myArray[1][0] = 'iPad';
myArray[1][1] = 2;

etc...

等等...

The string can vary in length but will always be in the format above. I have tried splitting and splicing and any other "ing" I can think of but I can't get it.

字符串的长度可以不同,但​​始终采用上述格式。我尝试过拆分和拼接以及我能想到的任何其他“ing”,但我无法理解。

Can anyone help please?

有人可以帮忙吗?

回答by I Hate Lazy

If the string is certain to be secure, the simplest would be to concatenat [and ]to the beginning and end, and then evalit.

如果字符串是一定是安全的,最简单的将是concatenat[]以开始和结束,然后eval它。

var arr = eval("[" + myString + "]");


If you wanted greater safety, use double quotes for your strings, and use JSON.parse()in the same way.

如果您想要更高的安全性,请为您的字符串使用双引号,并JSON.parse()以相同的方式使用。

var myString = '["Item", "Count"],["iPad",2],["Android",1]';

var arr = JSON.parse("[" + myString + "]");

This will limit you to supported JSON data types, but given your example string, it'll work fine.

这会将您限制为支持的 JSON 数据类型,但鉴于您的示例字符串,它会正常工作。

回答by Royi Namir

try this :

试试这个 :

JSON.parse("[['Item', 'Count'],['iPad',2],['Android',1]]".replace(/\'/g,"\""))

enter image description here

在此处输入图片说明

回答by bocapio

I tried to use eval, but in my case it doens't work... My need is convert a string into a array of objects. This is my string (a ajax request result):

我尝试使用 eval,但在我的情况下它不起作用......我需要将字符串转换为对象数组。这是我的字符串(ajax 请求结果):

{'printjob':{'bill_id':7998,'product_ids':[23703,23704,23705]}}

when I try:

当我尝试:

x = "{'printjob':{'bill_id':7998,'product_ids':[23703,23704,23705]}}";
eval(x);

I receive a "Unexpected token :" error.

我收到“意外令牌:”错误。

My solution was:

我的解决方案是:

x = "{'printjob':{'bill_id':7998,'product_ids':[23703,23704,23705]}}"; 
x = "temp = " + x + "; return temp;"
tempFunction = new Function (x);
finalArray = tempFunction();

now a have the object finalArray!

现在有对象 finalArray!

I hope to help

我希望有所帮助

回答by Yogesh Prajapati

write your code like

像这样写你的代码

var myString = "[['Item', 'Count'],['iPad',2],['Android',1]]";

and just

并且只是

 var arr = eval(myString);