简体   繁体   English

如何在控制台中接受用户(JS)的输入?

[英]How to accept an input in the console from the user (JS)?

I tried to create a JavaScript program that outputs the binary format of an English letter on input.我试图创建一个 JavaScript 程序,它在输入时输出英文字母的二进制格式。 I had to put the value in the code.我必须将值放入代码中。 How can the value be entered in the console when the program runs?程序运行时如何在控制台输入值?

function returnBinaryLetter(char) {
  return ((/^[a-z]$/).test(char)) ? char.charCodeAt(0).toString(2).padStart(8, '0') : 'Sorry, that is not a letter.'
}

// Something like:
// const input = consoleInputFunction('Enter a number.');
// console.log(returnBinaryLetter(input.toLowerCase()));

EDIT 1: This is not for a webpage.编辑 1:这不适用于网页。 This is a JS program which I will run using Node.js. I require a solution with just JS, not with some framework (if that is even possible, mentioning just to be specific).这是一个 JS 程序,我将使用 Node.js 运行它。我需要一个只有 JS 的解决方案,而不是一些框架(如果可能的话,只是为了具体提及)。

EDIT 2: I have made the code better after suggestions in Endothermic Dragon's answer.编辑 2:在 Endothermic Dragon 的回答中提出建议后,我改进了代码。

To directly answer your question, you would use prompt to get a user input in this case.要直接回答您的问题,在这种情况下,您将使用prompt获取用户输入。

However, you don't need all of that code.但是,您不需要所有这些代码。 Try this:尝试这个:

 function returnBinaryLetter(char) { if ((/^[az]$/).test(char)) { return char.charCodeAt(0).toString(2).padStart(8, '0') } else { return 'Sorry, that is not a letter.' } } var input = prompt('Enter letter to be converted to binary:').toLowerCase(); console.log(returnBinaryLetter(input))

While it may seem a bit intimidating, here's the whole thing broken down:虽然它可能看起来有点吓人,但这是整个事情的分解:

  1. Ask for an input using prompt , and convert it to lowercase.使用prompt请求输入,并将其转换为小写。
  2. Pass the character to the function returnBinaryLetter , and log the output.将字符传递给 function returnBinaryLetter ,并记录 output。

Now for the function returnBinaryLetter :现在对于 function returnBinaryLetter

  1. Check if it is a single lowercase letter, using some RegEx.使用一些正则表达式检查它是否是单个小写字母。
  2. If it is, return binary.如果是,则返回二进制。 Otherwise, return an error with a description.否则,返回带有描述的错误。

Hmm, but how does the binary conversion work?嗯,但是二进制转换是如何工作的呢?

  1. First, take the character and get its character code.首先,获取字符并获取其字符代码。
  2. Next, convert that code to binary.接下来,将该代码转换为二进制。
  3. Finally, pad the start so it is an 8-bit number.最后,填充开头,使其成为一个 8 位数字。 If it is not 8 digits, add on 0 s at the beginning until it is.如果不是 8 位,则在开头加0直到是。

Here, you can see that a more dynamic conversion looks much shorter, and cleaner as well, compared to manually entering about 28 lines of code.在这里,您可以看到与手动输入大约 28 行代码相比,更动态的转换看起来更短、更简洁。

Bonus:奖金:

Surprise, surprise.惊喜,惊喜。 You can further shorten it, Using a ternary operator, you can skip the if-else statement.您可以进一步缩短它,使用三元运算符,您可以跳过if-else语句。

 function returnBinaryLetter(char) { return ((/^[az]$/).test(char))? char.charCodeAt(0).toString(2).padStart(8, '0'): 'Sorry, that is not a letter.' } var input = prompt('Enter letter to be converted to binary:').toLowerCase(); console.log(returnBinaryLetter(input))

Now, it's a one-liner!现在,它是一条线!

A ternary operator is usually used within variables when you want to assign its value based on a condition.当您要根据条件为其赋值时,通常在变量中使用三元运算符。 The ternary operator first checks if the condition inside the brackets is true, and if it is, it returns the first statement (between ? and : ), and if not, it returns the second statement (after the : ).三元运算符首先检查括号内的条件是否为真,如果是,则返回第一个语句(在?:之间),如果不是,则返回第二个语句(在:之后)。 Pairing this with the return statement of a function, you get a one-liner function!将此与 function 的return语句配对,您将获得一个单行函数!

Feedback:反馈:

Since it seems that you are following CamelCase , I thought I would mention that function names should always start with a capital letter, along with each word after that also starting with a capital letter.由于您似乎在关注CamelCase ,我想我会提到 function 名称应始终以大写字母开头,之后的每个单词也应以大写字母开头。 Variables are different however - for variables, you do make the first letter lowercase, but make all the other words uppercase.然而,变量是不同的——对于变量,您确实将第一个字母设为小写,但将所有其他单词设为大写。 In addition, the function name returnBinaryLetter might seem intuitive to you, but not for anyone looking at the code.此外,function 名称returnBinaryLetter对您来说可能看起来很直观,但对于查看代码的任何人来说都不是。 A more intuitive name that exactly describes its function would be LowercaseLetterToBinary .准确描述其 function 的更直观的名称是LowercaseLetterToBinary

For NodeJS , You can use inquirer , which provides different kinds of prompts for the command line (such as text, list, checkbox etc).对于NodeJS ,您可以使用inquirer ,它为命令行提供不同类型的提示(例如文本、列表、复选框等)。

Prerequistes:先决条件:

  • Install it with npm install inquirer使用npm install inquirer

Example例子

const { prompt } = require("inquirer");

async main() {
    const binaryLetter = await prompt({
        type: 'input',
        name: 'letter',
        message: `What's your name >>`
    })
    .then(answer => returnBinaryLetter(answer['letter']));
}

main();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM