Tim*_*rce 0 javascript ecmascript-6
我正在用 CodeFights 练习我的 javascript,在我完成一个练习后,我看到了这个函数:
// Subject :
// Several people are standing in a row and need to be divided into two teams.
// The first person goes into team 1, the second goes into team 2,
// the third goes into team 1 again, the fourth into team 2, and so on.
// You are given an array of positive integers - the weights of the people.
// Return an array of two integers, where the first element is the total weight of
// team 1, and the second element is the total weight of team 2
// after the division is complete.
// Example :
// For a = [50, 60, 60, 45, 70], the output should be
// alternatingSums(a) = [180, 105].
// answer
alternatingSums = a => a.reduce((p,v,i) => (p[i&1]+=v,p), [0,0])
Run Code Online (Sandbox Code Playgroud)
我不明白什么p[i&1]+=v,p意思。
该&符号是一个按位二元运算符。
要了解会发生什么,您必须将每个项目转换为二进制。
| i (decimal) | i (binary) | i & 1 |
|-------------|------------|-------|
| 0 | 0 | 0 |
| 1 | 1 | 1 |
| 2 | 10 | 0 |
| 3 | 11 | 1 |
| 4 | 100 | 0 |
| 5 | 101 | 1 |
Run Code Online (Sandbox Code Playgroud)
实际上,每个偶数都将转换为 0,每个奇数都将转换为 1。
如果我试图达到那个结果,我个人会使用模数运算符 ( %)
p[i%2] += v;
Run Code Online (Sandbox Code Playgroud)
但这只是我。
(p[i&1]+=v,p)
Run Code Online (Sandbox Code Playgroud)
这就是说“执行此操作,然后返回p。它的简写为:
alternatingSums = a => a.reduce((p,v,i) => {
p[i&1]+=v;
return p;
},
[0,0])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |