Converting the array into a string array format

  Due to data transmission, sometimes we get is an array of strings (for example: str = '[ "a" , "b", "c", "d"]', written str = "[ 'a', 'b', 'c', 'd'] ", using the JSON.parse () when being given ). To such a character string is reduced to an array of objects, there are the following two methods.

1, eval () function converts

(1) eval () function computes a string, and executes the JavaScript code. We can use it to restore the string into an array.
const str = '["a", "b", "c", "d"]';
const arr =  eval('(' + str + ')');


console.log(str)    // '["a", "b", "c", "d"]'
console.log(arr)    // ["a", "b", "c", "d"]

2, using the JSON.parse () method converts

(1) Since the object is an array type, so we can use the JSON.parse () method to be converted into an array of objects.

const str = '["a", "b", "c", "d"]';
const arr =  JSON.parse(str);


console.log(str)    // '["a", "b", "c", "d"]'
console.log(arr)    // ["a", "b", "c", "d"]

When str = "[ 'a', 'b', 'c', 'd']" when, JSON.parse () error

 

 

 

 


 

Guess you like

Origin www.cnblogs.com/shy0113/p/12064590.html