JavaScript/array/reduce:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 引言 == == 示例 == 对象按照 key 进行排序,然后拼接 urn。 {{leftrightflex|<syntaxhighlight lang="javascript"> const foo = {name: 'kangkk', age: '…”
 
Kangkk​(留言 | 贡献)
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|”
标签:ReplaceText 移动版编辑 移动版网页编辑
 
(未显示同一用户的2个中间版本)
第1行: 第1行:
== 引言 ==
== 引言 ==
== 示例 ==
== 示例 ==
对象按照 key 进行排序
{{Double-columns|<syntaxhighlight lang="javascript">
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
  ),
  {}
);
</syntaxhighlight>|{{consoleout|<pre>{age: '18', key: 'await', name: 'kangkk'}
</pre>}}}}
对象按照 key 进行排序,然后拼接 urn。
对象按照 key 进行排序,然后拼接 urn。
{{leftrightflex|<syntaxhighlight lang="javascript">
{{Double-columns|<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>}}}}

2026年11月26日 (四) 06:43的最新版本

引言

示例

对象按照 key 进行排序

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
  ),
  {}
);
{age: '18', key: 'await', name: 'kangkk'}

对象按照 key 进行排序,然后拼接 urn。

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
  ),
  ''
);
'age=18&key=await&name=kangkk'