M
M
magogo2019-02-28 17:50:14
JavaScript
magogo, 2019-02-28 17:50:14

An infinite loop through an array. How to do it (Node js)?

There is an array It is necessary to create an infinite loop through the array in each integration of which, the existence of the number 65 will be checked (for example). as soon as this number 65 appears in the loop, the loop is broken and a notification is displayed in the console.
var Msg = [1, 6, 4, 88];

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Proskurin, 2019-02-28
@magogo

You can simply check the array as you add and remove values ​​from it. Either create a wrapper class through which you will add elements to the array, or override the methods in the array itself.

var Msg = [1, 6, 4, 88];

function checkArray(arr) {
   if (arr.includes(65)) {
      console.warn(65);
   }
}

Msg.push = function(e) {
   Array.prototype.push.call(Msg, e);
   checkArray(Msg);
};

as soon as elements are added to the element, a check will be made for the existence of the number 65.
The code can be finalized, check immediately in the push function, check when other methods are executed (pop, unshift , etc.).
But it's better to make a class that will have a private arr field, and public add/remove methods, etc.

H
hzzzzl, 2019-02-28
@hzzzzl

let interval = null
var Msg = [1, 6, 4, 88];

interval = setInterval(() => {
  if (Msg.includes(65)) {
    console.log(65)
    clearInterval(interval)
  }
}, 1000)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question