Just try to ask them to input their numbers or grade, separated by a comma and then you can split on it.
var arr = prompt("Enter your numbers").split(",")
Or, ask prompt ten times
var arr = [];
for(var i = 0; i < 10; i++)
arr.push(prompt("Enter a number");
If you want them to be numbers, just prefix prompt with +, so it becomes a number(provided they're actual numbers) or just do
arr = arr.map(Number);
Answer from Amit Joki on Stack OverflowJust try to ask them to input their numbers or grade, separated by a comma and then you can split on it.
var arr = prompt("Enter your numbers").split(",")
Or, ask prompt ten times
var arr = [];
for(var i = 0; i < 10; i++)
arr.push(prompt("Enter a number");
If you want them to be numbers, just prefix prompt with +, so it becomes a number(provided they're actual numbers) or just do
arr = arr.map(Number);
See the explanations in comments:
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter grade ' + (i+1))); // push the value into the array
}
alert('Full array: ' + arr.join(', ')); // alert the results
Adding User Input to the Array in JavaScript
How to save prompt input into array
How to create an array from names input through prompt?
Js Array Prompt Input Data - JavaScript
Just try to ask them to input their numbers or grade, separated by a comma and then you can split on it.
var arr = prompt("Enter your numbers").split(",")
Or, ask prompt ten times
var arr = [];
for(var i = 0; i < 10; i++)
arr.push(prompt("Enter a number");
If you want them to be numbers, just prefix prompt with +, so it becomes a number(provided they're actual numbers) or just do
arr = arr.map(Number);
See the explanations in comments:
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter grade ' + (i+1))); // push the value into the array
}
alert('Full array: ' + arr.join(', ')); // alert the results
So, I think the problem is that it's creating callbacks and the loop continues on so you're getting weird results. Using a variant of the Tiny CLI example, you can create a prompt with a question from the array and watch the line event to get the input, then repeat. Here's a quick example.
var read = require('readline'),
input = read.createInterface(process.stdin, process.stdout),
questions = ['test1: ', 'test2: '],
counter = 0;
input.setPrompt(questions[0]);
input.prompt();
input.on('line', function (a) {
console.log('answer: ', a);
counter++;
if (counter < questions.length) {
input.setPrompt(questions[counter]);
input.prompt();
} else {
process.exit(0);
}
});
I wrote some utility methods to help with this. Couple of added gems in here like it automatically writes the last values entered to a hidden file so a user can press enter
```
var async = require('async');
var fileUtils = require('../util/file-util');
var LAST_OPTIONS_FILE='./.last-options-file';
/**
* The prompt object type that is used by askSeries
* @typedef {Object} Prompt
* @property {string} key - is used as the variable name
* @property {string} [default] - is a default value so you can just press enter
* @property {string} [format] - validates input against a regex
* @property {string} [question] - use to make a more human readable prompt
* @property {boolean} [confirm] - will force user to confirm the value if it was found on the command line
* @property {boolean} [forceEnter] - if true, user must enter this value (last value is ignored)
*/
/**
* Asks user for input for each of the prompts
*
* <PRE>
* Example:
* askSeries([{key:"customerId"}, {key:"subscriptionId", "default":"blah"}], function(inputs) {
* console.log(inputs);
* });
* OUTPUT:
* customerId: 5
* subscriptionId [blah]: 9
* [ customerId: '5', subscriptionId: '9' ]
*
* askSeries([{key:"customerId", question:"Enter Customer Id", format: /\d+/}, {key:"subscriptionId", "default":"blah"}], function(inputs) {
* console.log(inputs);
* });
* OUTPUT:
* Enter Customer Id: abc
* It should match: /\d+/
* Enter Customer Id: 123
* subscriptionId [blah]:
* [ customerId: '123', subscriptionId: 'blah' ]
* </PRE>
*
* @param {Prompt[]} prompts - an array of Prompts which dictate what user should be asked
* @param {object} [argv] - if any of prompts .keys match argv it sets the default appropriately,
* argv will get all prompt .key values set on it as well
* @param {function} callback - signature is function(err,params)
*/
exports.askSeries = function(prompts,argv,callback) {
var input = {};
var lastVal = {};
if(typeof argv === 'function') { callback = argv; argv=null; }
lastVal = fileUtils.readJSONFileSync(LAST_OPTIONS_FILE);
if( !lastVal ) { lastVal = {}; }
console.log("LASTVAL", lastVal);
async.eachSeries(prompts, function(prompt, next) {
if( !prompt.key ) { callback(new Error("prompt doesn't have required 'key' param")); }
if( !prompt.confirm && argv && argv[prompt.key] ) {
input[prompt.key] = argv[prompt.key];
return next();
}
else {
var defaultVal = prompt.default;
if( argv && argv[prompt.key] ) { defaultVal = argv[prompt.key]; }
else if( !prompt.forceEnter && lastVal[prompt.key] ) { defaultVal = lastVal[prompt.key]; }
exports.ask( prompt.question || prompt.key, prompt.format || /.+|/, defaultVal, function(value) {
if( !value ) {
if( prompt.default ) {
value = prompt.default;
}
if( argv && argv[prompt.key] ) {
value = argv[prompt.key];
}
}
input[prompt.key] = value;
if( argv ) { argv[key] = value;}
next();
});
}
}, function(err) {
try {
var fileData = JSON.stringify(input);
fileUtils.writeToFile(LAST_OPTIONS_FILE, fileData );
}catch(err) { console.log("Unable to save entered values"); }
callback(err,input);
});
};
/**
* Prompts user for input
*
* @param {string} question prompt that is displayed to the user
* @param {string} [format] regex used to validate
* @param {string} [defaultVal] uses this value if enter is pressed
* @param callback is invoked with value input as callback(value);
*/
exports.ask = function ask(question, format, defaultVal, callback) {
var stdin = process.stdin, stdout = process.stdout;
if( typeof(format) === 'function' ) {
callback = format;
format = null;
}
if( typeof(defaultVal) === 'function') {
callback = defaultVal;
defaultVal = null;
}
stdin.resume();
var prompt = question;
if( defaultVal ) {
prompt += " [" + defaultVal + "]";
}
prompt += ": ";
stdout.write(prompt);
stdin.once('data', function(data) {
data = data.toString().trim();
if( !data && defaultVal ) {
data = defaultVal;
}
if (!format || format.test(data)) {
callback(data);
} else {
stdout.write("It should match: "+ format +"\n");
ask(question, format, callback);
}
});
};
/**
* Prints the usage from the <link Prompt> array.
* @param {Prompt[]} prompts - the array of prompts that will be asked if not entered on cmd line.
* @param {string} binaryName - if specified it puts it in the usage as <binaryName> [options]
* @param {boolean} [dontPrint] - if true, the usage will not be written to console
*/
exports.getUsage = function(prompts, binaryName, dontPrint) {
if(!binaryName) { binaryName = "program_name";}
var s = "\nUsage: \n./" + binaryName + " [options]\n\n options:\n";
console.log(prompts);
prompts.forEach( function(p) {
s += " --" + p.key;
if(p.question) { s += ": " + p.question;}
if(p.format) { s += ", format: " + p.format; }
s += "\n";
});
if( !dontPrint ) {
console.log( s );
}
return s;
};fs
```
You must be running that code at global scope in a browser. name is already defined in the global namespace on browsers. It's the name of the current window (a string). You can't shadow it in global scope via var, you have to use a scoping function or similar:
(function() {
var name = [];
for (var i = 0; i < 10; i++) { // Note 1
name[i] = prompt('Enter your name'); // Note 2
}
console.log(name);
})();
The lesson here: Avoid global scope. :-)
Note 1: You want < 10, not <= 10, if you only want 10 loops.
Note 2: You don't need to put () around the entire right-hand side of an assignment.
Please try this code :
var nm = new Array(10);
for(var i =0; i<10; i++){
nm[i]=prompt('Enter your name');
}
for(var i =0; i<10; i++){
document.write(nm[i] + '<br>');
}
We can't use variable name as 'name'. As well to get array value we have to provide index number in array, so in above using for loop to get all values.
Thanks...
The way you are doing it is close. You just need to put the prompt() outside the loop. Once you have the input to search, you then loop through your whole array of objects.
For example:
var nameInput = prompt();
for (i =0; i < array.length; i++){
if (nameInput == array[i].name) {
console.log(array[i].id)
}
}
Small explanation
Since your prompt is in a loop that also loops your array of objects, there can only be 1 "correct" answer at that given prompt point - whatever index (array[i].name) the loop is currently on.
To see more of what I mean run your current code and type jef the first time the prompt comes up, Steve the second time, and Ryan the third time- this way gets your IDs, but is probably not your intended outcome.
Try this. You need to sort through your array and perform a strong match, then return the ID.
function NameExists(strName,objectArray)
{
//convert to lower for type sensitive
strName = strName.toLowerCase();
for(var i = 0; i <objectArray.length; i++)
{
//convert to lower for type sensitive
var comparison = objectArray[i].Name.toLowerCase();
if(comparison.match(strName)==comparison)
return objectArray[i].id;
}
}
var givenNames = new Array();
var pattern = /[\w\d]{1,}/ig;
for(var i=0;i<10;i++){
var name = prompt("Enter some names. Only letters and digits are accepted!\nEntering an empty field stops asking","");
if(name && name.match(pattern)){givenNames.push(name);}
}
function displayNames(){
if(givenNames.length > 0){
document.getElementById("list").innerHTML = "<span style='color:Navy;font- weight:bold;'>Given names are:<\/span><br><br>" + givenNames.join("<br><br>");
} else {
document.getElementById("list").innerHTML = "<span style='color:Navy;font-weight:bold;'>Nothing has been given!<\/span>";
}
}
DEMO FIDDLE
See demo here
use your for loop condition to check count as well as input.
var givenNames = new Array();
var pattern = /[\w\d]{1,}/ig;
var name;
for ( var i=0; i<10 && name != ""; i++){
name = prompt("Enter some names. Only letters and digits are accepted!\nEntering an empty field stops asking", "");
if (name && name.match(pattern)) {
givenNames.push(name);
}
}
if (givenNames.length > 0) {
document.getElementById("list").innerHTML = "<span style='color:Navy;font- weight:bold;'>Given names are:<\/span><br><br>" + givenNames.join("<br><br>");
} else {
document.getElementById("list").innerHTML = "<span style='color:Navy;font-weight:bold;'>Nothing has been given!<\/span>";
}
if you are using do-while use do {...} while (++count < 10 && name != "") and if you want while use while (count++ < 10 && name != "" ) {...}