Convert javascript array to string

前端 未结 14 908
逝去的感伤
逝去的感伤 2020-11-29 16:41

I\'m trying to iterate over a \"value\" list and convert it into a string. Here is the code:

var blkstr = $.each(value, function(idx2,val2) {                        


        
14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 17:31

    this's my function, convert object or array to json

    function obj2json(_data){
        str = '{ ';
        first = true;
        $.each(_data, function(i, v) { 
            if(first != true)
                str += ",";
            else first = false;
            if ($.type(v)== 'object' )
                str += "'" + i + "':" + obj2arr(v) ;
            else if ($.type(v)== 'array')
                str += "'" + i + "':" + obj2arr(v) ;
            else{
                str +=  "'" + i + "':'" + v + "'";
            }
        });
        return str+= '}';
    }
    

    i just edit to v0.2 ^.^

     function obj2json(_data){
        str = (($.type(_data)== 'array')?'[ ': '{ ');
        first = true;
        $.each(_data, function(i, v) { 
            if(first != true)
                str += ",";
            else first = false;
            if ($.type(v)== 'object' )
                str += '"' + i + '":' + obj2json(v) ;
            else if ($.type(v)== 'array')
                str += '"' + i + '":' + obj2json(v) ;
            else{
                if($.type(_data)== 'array')
                    str += '"' + v + '"';
                else
                    str +=  '"' + i + '":"' + v + '"';
            }
        });
        return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
    }
    

提交回复
热议问题