Tell me how to implement the next idea. There is an input to which, separated by commas, the numbers are entered (the age to be written in some variable for further work) and the label (for example) displays: "Number of people: ..".

For example: Enter the age: 24, 22, 10 (24 years, 22 years, 10 years). And displayed -> Number of people: 3

  • 2
    input.value.split(',').length by comma and count: input.value.split(',').length . With an empty entry, however, will display 1 - vp_arth

1 answer 1

Like that:

 function result(data) { // Убираем пробелы и превращаем в массив var arrayData = data.replace(/\ /g, '').split(','); // Считаем количество записей if(data == ''){var data_length = 0}else{var data_length = arrayData.length}; // Выводим количество записей console.log('Количество человек: '+data_length); // Выводим список чисел console.log('Возрасты: '+arrayData); //Выводим каждое число for(var i = 0; i < data_length; i++){ console.log('Возраст №'+i+': '+arrayData[i]); } } 
 <input type="text" id="old"> <button onclick="result(document.querySelector('#old').value)">Количество людей</button> 

But the technique should be improved, since the user can enter letters and other meanings.