Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

javascript - What is the logic behind "prop: props[ i % props.length] inside a .map()"?

I am trying to understand...

// 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],
  });
});

Specifically

  • What props[i % props.length] does?
  • What prop will get in the final?
question from:https://stackoverflow.com/questions/66059824/what-is-the-logic-behind-prop-props-i-props-length-inside-a-map

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The % operator is JavaScript's syntax for the mathematical Remainder operator - it's often referred to as the "modulo" operator but this is technically incorrect because "remainder" and "modulo" are different when dealing with negative numbers.

But in this case, we're dealing with positive array indexes, so "modulo" and "remainder" are interchangable.

"x mod y" - or "The Modulo of x over y" can be described as "The remainder of x divided by y". In programming this is used for many things, but in this case it's to get a valid index into props from i (where i is an index into groups, and not props - so i cannot be used to index props directly).


The i parameter is in the range of [0-groups.length] (i.e. not props.length!), while props presumably has a props.length that's smaller than groups.length.

So if you have:

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

Then the output will be:

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
];

As an aside, I die inside somewhat whenever I see someone use the identifier props in JavaScript. I know it's a term of art in the React ecosystem, but it's still... horrible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...