开发者

How do I convert Javascript String into an Array?

This entire list is provided as a single String variable.

    instruments = '["guitar","bass","drums","keyboard"]';

How do I convert the String into an array so I can print each item out in its own individual div tag?

    for(var i=0;i<instruments.length;i++){
        document.write("<div>"+instruments[i]+"</div>");
        }开发者_运维问答


If the string contains a valid JSON array (like in your example) you could use JSON.parse, like this:

instrumentsString = '["guitar","bass","drums","keyboard"]';
instrumentsArray = JSON.parse(instrumentsString);

Do note that all browsers does not have the JSON.parse-function, so you might have to include an implementation. jQuery come with one for example and you can also use Douglas Crockfords json2.


In this case you could actually use a JSON parser:

JSON.parse('["guitar","bass","drums","keyboard"]');
// -> ["guitar", "bass", "drums", "keyboard"]


Given your instruments variable:

Use JSON.parse() like so:

var instrumentsArray = JSON.parse(instruments);

Or, do something like this:

instruments = instruments.replace(/\[(.*?)\]/, "$1");
var instrumentsArray = instruments.split(/,/);

Then just use a for loop to loop through the array:

for (var i = 0; i < instrumentsArray.length; i++) {
    // instrumentsArray[i] is the current element
}


You can eval it to get the array out.

var instruments = '["guitar","bass","drums","keyboard"]';
var instruments_array = eval(instruments);


if the string list has any seperator then simply use split function.

Example:

var myString = "zero one two three four";

var mySplitResult = myString.split(" ");

for(i = 0; i < mySplitResult.length; i++){
    document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
}


you can simply do an eval on it

instruments = '["guitar","bass","drums","keyboard"]';
var instrumentsArray = eval(instruments);

then

for(var i=0;i<instrumentsArray.length;i++){
    document.write("<div>"+instrumentsArray[i]+"</div>");
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜