【问题标题】:What is the logic behind "prop: props[ i % props.length] inside a .map()"?“prop:props [ i % props.length] inside a .map()”背后的逻辑是什么?
【发布时间】:2021-05-09 14:11:50
【问题描述】:

我正在努力理解...

// group is an array of numbers coming from an api

const arr = group.map((el, i) => {
  return new obj({
    element: el,
    prop: props[i % props.length],
  });
});

具体

  • props[i % props.length] 做什么?
  • prop 将在决赛中获得什么?

【问题讨论】:

  • 什么是group
  • 这是一种在group 项目中循环重复props 的方法。如果 props[1,2,3] 并且组有 9 个项目,则对象的输出数组将有 prop:1prop:2prop:3prop:1
  • 人,数组在自己内部交互?那我真的很笨,因为我真的不知道i % props.length在做什么......至少我知道这可能是一个用作索引的数字但是这个% props.length是我真正不知道的部分不知道那里在做什么......可能是一些疯狂的数学东西......
  • @VokzGnakx map 内没有迭代。这是直接的O(1) indexer getter 调用。
  • @Dai,是的,你是对的。为了避免混淆,我也删除了我的 cmets。谢谢

标签: javascript arrays ecmascript-6 array.prototype.map


【解决方案1】:

为了简化理解

i % props.length

// 0 % 8 === 0
// 1 % 8 === 1
// 2 % 8 === 2
// 3 % 8 === 3
// 4 % 8 === 4
// 5 % 8 === 5
// 6 % 8 === 6
// 7 % 8 === 7
// 8 % 8 === 0 - never gets here.
props[0]
props[1]
props[2]
props[3]
props[4]
props[5]
props[6]
props[7]

它可能刚刚写成:

const arr = group.map((el, i) => new obj({
  element: el,
  prop: props[i]
}));

【讨论】:

  • 我们不知道 什么 props.length 是 - 也不知道 group.length。您的回答仅在props.length === group.length 有效但尚未成立。
  • 现在我明白了,这就像在两个长度内同时循环重复,很酷的东西。我从来没有看起来像那样的东西。谢谢!
【解决方案2】:

The % operator is JavaScript's syntax for the mathematical Remainder operator - 它通常被称为“模”运算符,但这是技术上不正确的,因为“余数”和“模”在处理负数时是不同的。

但在本例中,我们处理的是正数组索引,因此“模”和“余数”是可以互换的。

“x mod y” - 或“The Modulo of x over y”可以描述为“x 的余数除以 y”。在编程中,这用于许多事情,但在这种情况下,它是从i 获取到props 的有效索引(其中i 是到groups 的索引,而不是 @ 987654328@ - 所以i 不能直接用于索引props)。


i 参数在[0-groups.length] 的范围内(即不是 props.length!),而props 可能有一个小于groups.lengthprops.length

如果你有:

const groups = [ 'a', 'b', 'c', 'd', 'e', 'f' ]; // length: 6
const props  = [ 0, 1, 2 ]; // length: 3

那么输出将是:

const arr = [
    { el: 'a', prop: 0 },        // i = 0, i % 3 == 0
    { el: 'b', prop: 1 },        // i = 1, i % 3 == 1
    { el: 'c', prop: 2 },        // i = 2, i % 3 == 2
    { el: 'd', prop: 0 },        // i = 3, i % 3 == 0
    { el: 'e', prop: 1 },        // i = 4, i % 3 == 1
    { el: 'f', prop: 2 },        // i = 5, i % 3 == 2
];

顺便说一句,每当我看到有人在 JavaScript 中使用标识符 props 时,我都会有点死心。我知道这是 React 生态系统中的一个艺术术语,但它仍然......很糟糕。

【讨论】:

  • 你知道有时我们可以用 JS 获得一些疯狂的微风......哈哈,谢谢你澄清这一点,现在我明白了! @戴
  • 不知道余数和模数之间的区别。感谢您清除它!
  • @jBuchholz 范围内的任何技术专家(包括我自己)都知道技术上正确the best kind of correct!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 2017-10-17
  • 1970-01-01
  • 2018-06-18
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多