表达式“ p [i& 1] + = v,p”是什么意思?

编程入门 行业动态 更新时间:2024-10-25 00:28:59
本文介绍了表达式“ p [i& 1] + = v,p”是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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;

但这就是我。

另一部分是用逗号分隔两个语句:


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”是什么意思?

本文发布于:2023-08-01 04:21:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1265172.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!