將對象轉換爲字符串

如何將JavaScript對象轉換爲字符串? javascript

例: java

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)

輸出: jquery

對象{a = 1,b = 2} //很是好的可讀輸出:)
Item:[object Object] //不知道里面是什麼:( json


#1樓

看一下jQuery-JSON插件 數組

從本質上講,它使用JSON.stringify,但若是瀏覽器沒有實現,則會回退到本身的解析器。 瀏覽器


#2樓

若是你知道對象只是一個布爾,日期,字符串,數字等... javascript String()函數工做得很好。 我最近發現這對於處理來自jquery的$ .each函數的值頗有用。 app

例如,如下內容會將「value」中的全部項目轉換爲字符串: 函數

$.each(this, function (name, value) {
  alert(String(value));
});

更多細節在這裏: 測試

http://www.w3schools.com/jsref/jsref_string.asp ui


#3樓

由於firefox沒有將某些對象字符串化爲屏幕對象; 若是你想獲得相同的結果,例如: JSON.stringify(obj)

function objToString (obj) {
    var tabjson=[];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            tabjson.push('"'+p +'"'+ ':' + obj[p]);
        }
    }  tabjson.push()
    return '{'+tabjson.join(',')+'}';
}

#4樓

這裏沒有一個解決方案適合我。 JSON.stringify彷佛是不少人所說的,但它削減了函數,對於我在測試時嘗試的一些對象和數組看起來很糟糕。

我製做了本身的解決方案,至少在Chrome中有效。 在此處發佈,以便在Google上查找此內容的任何人均可以找到它。

//Make an object a string that evaluates to an equivalent object
//  Note that eval() seems tricky and sometimes you have to do
//  something like eval("a = " + yourString), then use the value
//  of a.
//
//  Also this leaves extra commas after everything, but JavaScript
//  ignores them.
function convertToText(obj) {
    //create an array that will later be joined into a string.
    var string = [];

    //is object
    //    Both arrays and objects seem to return "object"
    //    when typeof(obj) is applied to them. So instead
    //    I am checking to see if they have the property
    //    join, which normal objects don't have but
    //    arrays do.
    if (typeof(obj) == "object" && (obj.join == undefined)) {
        string.push("{");
        for (prop in obj) {
            string.push(prop, ": ", convertToText(obj[prop]), ",");
        };
        string.push("}");

    //is array
    } else if (typeof(obj) == "object" && !(obj.join == undefined)) {
        string.push("[")
        for(prop in obj) {
            string.push(convertToText(obj[prop]), ",");
        }
        string.push("]")

    //is function
    } else if (typeof(obj) == "function") {
        string.push(obj.toString())

    //all other values can be done with JSON.stringify
    } else {
        string.push(JSON.stringify(obj))
    }

    return string.join("")
}

編輯:我知道這個代碼能夠改進,但歷來沒有作過。 用戶安德烈提出的改善這裏與評論:

這是一個稍微改變的代碼,它能夠處理'null'和'undefined',也不會添加過多的逗號。

使用它須要您自擔風險,由於我根本沒有驗證過。 做爲評論,請隨意建議任何其餘改進。


#5樓

若是您只是輸出到控制檯,則可使用console.log('string:', obj) 。 注意逗號

相關文章
相關標籤/搜索