JavaScript/array/reduce:修订间差异
来自康健生活
| 第4行: | 第4行: | ||
{{leftrightflex|<syntaxhighlight lang="javascript"> | {{leftrightflex|<syntaxhighlight lang="javascript"> | ||
const foo = {name: 'kangkk', age: '18', key: 'await'}; | const foo = {name: 'kangkk', age: '18', key: 'await'}; | ||
const obj = Object.keys(foo).sort().reduce((r, k, i) => (r[encodeURIComponent(k)] = encodeURIComponent(foo[k]), r), {}) | const obj = Object.keys(foo) | ||
.sort() | |||
.reduce( | |||
(r, k, i) => (r[encodeURIComponent(k)] = encodeURIComponent(foo[k]), | |||
r | |||
), | |||
{} | |||
); | |||
</syntaxhighlight>|{{consoleout|<pre>{age: '18', key: 'await', name: 'kangkk'} | </syntaxhighlight>|{{consoleout|<pre>{age: '18', key: 'await', name: 'kangkk'} | ||
</pre>}}}} | </pre>}}}} | ||
| 第11行: | 第18行: | ||
{{leftrightflex|<syntaxhighlight lang="javascript"> | {{leftrightflex|<syntaxhighlight lang="javascript"> | ||
const foo = {name: 'kangkk', age: '18', key: 'await'}; | const foo = {name: 'kangkk', age: '18', key: 'await'}; | ||
const str = Object.keys(foo).sort().reduce((r, k, i) => (r = r + (i ? '&' : '') + encodeURIComponent(k) + '=' + encodeURIComponent(foo[k]), r), ''); | const str = Object.keys(foo) | ||
.sort() | |||
.reduce( | |||
(r, k, i) => (r = r + (i ? '&' : '') + encodeURIComponent(k) + '=' + encodeURIComponent(foo[k]), | |||
r | |||
), | |||
'' | |||
); | |||
</syntaxhighlight>|{{consoleout|<pre>'age=18&key=await&name=kangkk' | </syntaxhighlight>|{{consoleout|<pre>'age=18&key=await&name=kangkk' | ||
</pre>}}}} | </pre>}}}} | ||