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]
這不僅僅是在控制檯中觀看。這個想法是,這個字符串被用在ajax請求中,然後另一端解析它,並且需要一個數組,但是取而代之。
因爲[參數](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments)是一個像Object這樣的數組,而不是一個Array。你可以做'[] .slice.call'而不是'Array.prototype.slice.call' – C5H8NNaO4
是的,那會更短,味精更少。謝謝。 – Paul
你還可以做些什麼:'arguments.toJSON = [] .slice; console.log(JSON.stringify(arguments));':-) – Bergi