开发者

A better javascript to string function?

Before I go and create this myself, I thought I'd see if anyone knows a library that does this.

I'm looking for a function that will take something in Javascript, be it an array, an associative array, a number, or even a string, and conv开发者_运维技巧ert it to something that looks like it. For example:

toString([1,2,3]) === '[1, 2, 3]'
toString([[1,2], [2,4], [3,6]]) === '[[1,2], [2,4], [3,6]]'
toString(23) === '23'
toString('hello world') === 'hello world'
toString({'one': 1, 'two': 2, 'three': 3}) === "{'one': 1, 'two': 2, 'three': 3}"


As mentioned in the comments (and I'm surprised nobody actually posted it as an answer), JSON.stringify() is the method that you're looking for. It's supported natively in most browsers these days, but you can also implement it in the browsers that don't support it using json2.js.

Working demo: http://jsfiddle.net/AndyE/WXfzJ/

The only exception is function objects, which won't be stringified by JSON. However, Function.prototype.toString will return a re-parseable string representation of the function, although you should be aware that white-space and comments may be stripped depending on the browser:

function moo() {
    alert('cow says moo!');
}

alert(moo.toString());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜