开发者

any alternative of firefox's toSource() function

开发者 https://www.devze.com 2023-04-04 06:15 出处:网络
I am using dynarch calendar and I want the selected dates ranges to be converted into strings like as firefox\'s toSource() do.

I am using dynarch calendar and I want the selected dates ranges to be converted into strings like as firefox's toSource() do.

Example of converting an two-dimensional array into source:

[20110917, [20110920, 20110922], 20110923, [20110925, 20110926]]

any alter开发者_StackOverflow社区native to get this same output in other browsers too..???

I am already using jQuery 1.6.2 library. So, I don't want any other library or bigger script to get this function to work.


You tagged it json already, modern browsers support the JSON.stringify and JSON.parse methods for converting data to text (JSON representation) and text to data respectively.

In your case:

var arr = [20110917, [20110920, 20110922], 20110923, [20110925, 20110926]];

// yields: [20110917,[20110920,20110922],20110923,[20110925,20110926]]
console.log(JSON.stringify(arr));

Alternative method:

function arr_to_string(data) {
    if (data instanceof Array) {
        var arr = [];
        for (var i=0; i<data.length; i++) {
            arr.push(arr_to_string(data[i]));
        }
        return "[" + arr.join(",") + "]";
    }
    // Warning: we expect all array elements to be digits, do not use this if the
    // data can be a random string
    return data;
}
console.log(arr_to_string(arr));
0

精彩评论

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

关注公众号