i would like to convert this string:
'[
['Row1 of first array', 'Row2 of first array'],
['Row1 of 2nd array', 'Row2 of 2nd array']
]'
Into an array with three arrays of one dimension and two items.
My expected output is an array with 2 elements:
And every array has two elements inside.
Is there any in Jquery to do this conversion?
That's not a valid string -- you're nesting single quotes inside of single quotes. However, if you convert the string into one using double quotes on the inside:
str = '[ ["Row1 of first array", "Row2 of first array"], ["Row1 of 2nd array", "Row2 of 2nd array"] ]'
then you could simply parse it as a JSON object:
arr = $.parseJSON(str); // returns a two-dimensional array
This is far, FAR safer than using eval
, which should only be done when you know EXACTLY what's inside the string, and even then, it's a sign of a lazy developer. When using parseJSON
, you know that you're getting either an object or an array when you're done -- when using eval
, anything might happen.
I guess eval will work:
var str = eval("[['Row1 of first array', 'Row2 of first array'],['Row1 of 2nd array', 'Row2 of 2nd array']]");
console.log(str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.