Javascript/Jquery Convert string to array

后端 未结 4 1536
北恋
北恋 2021-02-04 03:07

i have a string

var traingIds = \"${triningIdArray}\";  // ${triningIdArray} this value getting from server 
alert(traingIds)  // alerts [1,2]
var type = typeof         


        
4条回答
  •  悲&欢浪女
    2021-02-04 03:56

    Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.

    var test = "[1,2]";
    parsedTest = JSON.parse(test); //an array [1,2]
    
    //access like and array
    console.log(parsedTest[0]); //1
    console.log(parsedTest[1]); //2
    

提交回复
热议问题