Javascript/Jquery Convert string to array

后端 未结 4 1535
北恋
北恋 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:52

    Change

    var trainindIdArray = traingIds.split(',');

    to

    var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');

    That will basically remove [ and ] and then split the string

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-04 03:56

    check this out :)

    var traingIds = "[1,2]";  // ${triningIdArray} this value getting from server 
    alert(traingIds);  // alerts [1,2]
    var type = typeof(traingIds);
    alert(type);   // // alerts String
    
    //remove square brackets
    traingIds = traingIds.replace('[','');
    traingIds = traingIds.replace(']','');
    alert(traingIds);  // alerts 1,2        
    var trainindIdArray = traingIds.split(',');
    
    ​for(i = 0; i< trainindIdArray.length; i++){
        alert(trainindIdArray[i]); //outputs individual numbers in array
        }​ 
    
    0 讨论(0)
  • 2021-02-04 04:03

    Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:

    var traingIds = ${triningIdArray};
    

    not

    var traingIds = "${triningIdArray}";
    
    0 讨论(0)
提交回复
热议问题