2013-07-09 28 views
5

爲什麼不將參數串化爲數組?JSON.stringify(參數)發生了什麼?

是否有一個不太冗長的方式來使參數像數組一樣串行化?

function wtf(){ 
    console.log(JSON.stringify(arguments)); 
    // the ugly workaround 
    console.log(JSON.stringify(Array.prototype.slice.call(arguments))); 
} 

wtf(1,2,3,4); 
--> 
{"0":1,"1":2,"2":3,"3":4} 
[1,2,3,4] 


wtf.apply(null, [1,2,3,4]); 
--> 
{"0":1,"1":2,"2":3,"3":4} 
[1,2,3,4] 

http://jsfiddle.net/w7SQF/

這不僅僅是在控制檯中觀看。這個想法是,這個字符串被用在ajax請求中,然後另一端解析它,並且需要一個數組,但是取而代之。

+6

因爲[參數](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments)是一個像Object這樣的數組,而不是一個Array。你可以做'[] .slice.call'而不是'Array.prototype.slice.call' – C5H8NNaO4

+0

是的,那會更短,味精更少。謝謝。 – Paul

+4

你還可以做些什麼:'arguments.toJSON = [] .slice; console.log(JSON.stringify(arguments));':-) – Bergi

回答

4

發生這種情況是因爲參數是而不是數組,而是array-like object。您的解決方法是將其轉換爲實際的數組。 JSON.stringify的行爲與此處設計的一樣,但不是很直觀。