How correctly when filling an array through the prompt , if the user has not entered a value, output the prompt until the user enters some value?

 function addName() { var arrContainer = document.getElementById('array'); var arr = []; // создаСм массив for(var i=0; i < 5; i++) { arr[i] = prompt('Π’Π²Π΅Π΄ΠΈΡ‚Π΅ любоС имя', +i); // ЗаполняСм массив if(arr[i] === null) { // Ссли Π½Π°ΠΆΠΈΠΌΠ°Π΅ΠΌ "ΠžΡ‚ΠΌΠ΅Π½Π°" alert('ΠžΡ‚ΠΌΠ΅Π½Π°'); return; } if(arr[i] === '') { // Ссли имя Π½Π΅ Π²Π²Π΅Π΄Π΅Π½ΠΎ alert('Π’Ρ‹ Π½Π΅ ΡƒΠΊΠ°Π·Π°Π»ΠΈ имя'); arr[i] = prompt('Π’Π²Π΅Π΄ΠΈΡ‚Π΅ любоС имя'); } } arrContainer.innerHTML = ''; arrContainer.innerHTML = arr; console.log(arr); // Π’Ρ‹Π²ΠΎΠ΄ΠΈΠΌ массив Ρ†Π΅Π»ΠΈΠΊΠΎΠΌ } 
  • so in the last question the problem was already solved by calling the promt again - Grundy
  • Yes, return prompt(...); And what is arrContainer ? - Mr. Black

2 answers 2

It would also be necessary to consider unsuccessful attempts in order not to torture with the alerts of a poor user, who changed his mind to enter names.

 function addName() { var arrContainer = document.getElementById('array') ,n = 5 // число элСмСнтов массива ,max = 3 // макс. число пСрСзапросов ,att // счётчик ΠΏΠΎΠΏΡ‹Ρ‚ΠΎΠΊ ,i // индСкс элСмСнта массива ,greet = '' // сообщСниС ΠΏΡ€ΠΈ запросС ,arr = [] // создаСм массив ; for(i=0; i<n; i++) { for( att=0; att<max;) { greet = 'Π’Π²Π΅Π΄ΠΈΡ‚Π΅ любоС имя β„–'+(i+1); if(att++ > 0) greet += ' (ΠΏΠΎΠΏΡ‹Ρ‚ΠΊΠ° '+att+' ΠΈΠ· '+max+')'; arr[i] = prompt( greet); // ЗаполняСм массив if (null !== arr[i] && arr[i].length) break; if(att === max) { alert("Ой, всё"); return false; } } } arrContainer.innerHTML = JSON.stringify(arr); return arr; } addName(); 
 <div id="array"></div> 

    I do not pretend to a beautiful code, here is the solution to the forehead:

     function addName() { var arrContainer = document.getElementById('array'); var arr = []; // создаСм массив for(var i=0; i < 5; i++) { while( typeof (arr[i] = prompt('Π’Π²Π΅Π΄ΠΈΡ‚Π΅ любоС имя β„–'+i)) != 'string' || arr[i].length == 0 ); } arrContainer.innerHTML = arr; console.log(arr); // Π’Ρ‹Π²ΠΎΠ΄ΠΈΠΌ массив Ρ†Π΅Π»ΠΈΠΊΠΎΠΌ } 

    Demo: http://codepen.io/anon/pen/WxdvOy

    Who will solve the trick with typeof ? :)

    • Well, typeof will be cast to false in the while condition until it is equal to the string or equal to the length 0, but how is it that while without a body - I don't understand yet) - user190134
    • when the prompt is canceled, it will return null and typeof will not be equal to string - Grundy