An array is given:

var fruits = ["banana", "cherry", "melon", "strawberry"]; 

It is necessary to iterate it using the while loop and for all values ​​with an even index, change the register to the upper one.

Wrote the following code:

 var i; while (i < fruits.length - 1) { if (fruits[i] % 2 === 0) { fruits[i].toUpperCase(''); } else { continue; } i++; } 

What am I doing wrong?

  • You have the result fruits[i].toUpperCase(''); not assigned anywhere. It is necessary so fruits[i]=fruits[i].toUpperCase(''); - Stepan Kasyanenko

4 answers 4

  1. It is necessary to count the remainder of division from the index i , and not from the array element. Better yet, make i accept only even values. For example, increasing the value of i immediately by 2
  2. Although it is not quite an error, but the toUpperCase method does not accept any parameters
  3. The toUpperCase method does not change the string, but returns a new one, therefore the execution result must be assigned back to fruits[i]
  4. else { continue; } else { continue; } without increasing i can easily lead to looping, and why is it here?
  5. You need to go to i < fruits.length , so as not to lose the last even element in an array of odd length

The result is:

 var fruits = ["banana", "cherry", "melon", "strawberry"]; var i = 0; while (i < fruits.length) { fruits[i] = fruits[i].toUpperCase(); i += 2; } console.log(fruits); 


If the task is to use while , then the code is as follows, but generally for it looks more appropriate here:

 var fruits = ["banana", "cherry", "melon", "strawberry"]; for (var i = 0; i < fruits.length; i += 2) fruits[i] = fruits[i].toUpperCase(); console.log(fruits); 

  • Yes, for and somehow clearer, but the task really was to consolidate while. Though I figured out how to apply it correctly. Thank! - Alice Guly
  • @AlisaGuly do not use while, this is antediluvian method. - EVG
  • @EVG where is this categorical? If, for example, you need to iterate while a condition is met, then what will you use instead of while (condition) ? - Regent
  • @EVG is my starting level, I'm just trying to master my homework. What was asked, I understand it :) - Alice Guliy
  • @Regent well, except perhaps for this, but if you can pervert, you can use an infinite loop through setInterval until the condition is fulfilled and then kill the function)). Although setInterval is 2 times slower, it seems there is 4 ms vs. 2ms in while))). In any case, I rarely meet a practitioner while) - EVG

 let fruits = ["banana", "cherry", "melon", "strawberry"]; console.info(fruits.map((el, i) => !(i % 2) ? el.toUpperCase() : el)); 

     var fruits = ["banana ", "cherry ", "melon ", "strawberry "]; var i = -1; while (++i < fruits.length) { if (!(i % 2)) { fruits[i] = fruits[i].toUpperCase(); } } console.log(fruits); 

       var fruits = ["banana", "cherry", "melon", "strawberry"]; for (var i = 0; i < fruits.length; i++) { i%2 != 0 ? fruits[i] = fruits[i].toUpperCase() : '' } console.log(fruits)