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
202 views
in Technique[技术] by (71.8m points)

javascript - Loop that stops when condition is met, that sets state depending on window scroll

I managed to get an array of refs of sections on my page that looks like this:

(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {current: div.single-section}
1: {current: div.single-section}
2: {current: div.single-section}
3: {current: div.single-section}
4: {current: div.single-section}
5: {current: div.single-section}
length: 6
__proto__: Array(0)

I passed it from Sections component to CategoryNav component, where in Navbar I have categories that are corresponding to those sections. Every single-section has data-id that is equal to category id. Now, my goal is to, depending on what section is on screen give the corresponding category in navbar class "active". That all I did and it works. The problem which I have is this function on eventListener scroll that sets my state to data-id of single section which will give corresponding category with this id class "active" and that all I have done. The only problem I have is this function:

const activeCategory = () => {
    for (let i = 0; i < myArr.length; i++) {
      if (
        window.pageYOffset > myArr[i].current.offsetTop &&
        myArr[i].current.offsetTop < myArr[i].current.offsetTop + myArr[i].current.getBoundingClientRect().height
      );
      {
        setCurrentCategory(myArr[i].current.dataset.id);
        break;
      }
    }
  };

I want to loop this array, and check if first section's is basically on the screen, if it is, it sets my state to dataset.id of this section, if it is not, it goes to next item. I wrote this, but it stays on first item, no mather what is on the screen, it just doesn't go to next item. Can anyone help?

question from:https://stackoverflow.com/questions/65830540/loop-that-stops-when-condition-is-met-that-sets-state-depending-on-window-scrol

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

1 Reply

0 votes
by (71.8m points)

While trying on the code below, it also stops at first iteration with ; right after if(i == 73). As stated by @VLAZ. The same thing happens as the issue you report. Please double check this ; is not your problem.

/* All prime numbers below 100 */
const limit = 100;
const isPrime = num => {
    for(let i = 2, s = Math.sqrt(num); i <= s; i++)
        if(num % i === 0) return false; 
    return num > 1;
}

for (let i = 0; i < limit; i++) {
  if(isPrime(i)) {
    console.log(i);
    if(i == 73); {
      break; // break loop before given `i < limit` condition
    }
  }
}

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

...