表达式“ p [i& 1] + = v,p”是什么意思? [英] What does the expression `p[i&1]+=v,p` mean?
问题描述
我正在使用CodeFights练习javascript,完成练习后,我看到了此功能的结果:
I was practicing my javascript with CodeFights and after I finished an exercise I saw this function as a result:
// 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])
我不明白 p [i& 1] + = v,p
是什么意思。
推荐答案
&
符号是按位二进制运算符。
The &
symbol is a bitwise binary operator.
要理解会发生什么,您必须将每个项目转换为二进制。
To understand what would happen, you have to convert each item to binary.
| i (decimal) | i (binary) | i & 1 |
|-------------|------------|-------|
| 0 | 0 | 0 |
| 1 | 1 | 1 |
| 2 | 10 | 0 |
| 3 | 11 | 1 |
| 4 | 100 | 0 |
| 5 | 101 | 1 |
有效地,每个偶数将转换为0,每个奇数将转换为1。
Effectively, every even number will be transformed to 0, and every odd number will be transformed to 1.
如果我想实现这一目标,我个人将使用模运算符(%
)
If I was trying to achieve that outcome, I personally would have used the modulus operator (%
)
p[i%2] += v;
但这就是我。
< hr />
另一部分是用逗号分隔两个语句:
The other part is that there are two statements separated by a comma:
(p[i&1]+=v,p)
这是说执行此操作,然后返回 p
。它的简写为:
That's saying "Perform this action, then return p
. It's shorthand for:
alternatingSums = a => a.reduce((p,v,i) => {
p[i&1]+=v;
return p;
},
[0,0])
这篇关于表达式“ p [i& 1] + = v,p”是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!