V
V
Vit132021-06-22 16:52:39
JavaScript
Vit13, 2021-06-22 16:52:39

It does not work quite correctly, why does it sort through all the numbers?

Given an array of numbers. Check that this array contains the number 5. If there is, print 'yes', and if not, print 'no'.

Here is my code:
============================================= ================================================= ===========
let arr = [2, 55, 6, 65, 65, 65, 65, 65, 6, 4, 84, 5];
for(let i = 0; i < arr.length; i++){
if (arr[i] == 5)
document.write('Yes');

else
document.write('No');

}
The problem is that the browser displays the following response: NoNoNoNoNoNoNoNoNoNoNoNoYes Is
it necessary or yes or no

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WapSter, 2021-06-22
@Vit13

Well, you put the output into the loop at each iteration. Take it out for a cycle.

let arr = [2, 55, 6, 65, 65, 65, 65, 65, 6, 4, 84, 5];
let result = 'Нет';
for(let i = 0; i < arr.length; i++){
  if (arr[i] == 5) result = 'Есть';
}
document.write(result);

A shorter example
let arr = [2, 55, 6, 65, 65, 65, 65, 65, 6, 4, 84, 5];
const result = arr.some(n => n === 5);
document.body.textContent = result ? 'Есть' : 'Нет';

E
Egor Zhivagin, 2021-06-22
@Krasnodar_etc

Because you are calling document.write on every iteration of the loop

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question