在 JavaScript 中获取用户输入
本文将帮助你了解如何在 JavaScript 中获取用户输入。
有两种方法可以在 JavaScript 中获取用户输入,具体取决于你是要从浏览器还是 NodeJS 输入。本指南将帮助你学习两者。
要要求来自浏览器的用户输入,你必须使用浏览器提供的 prompt()
方法。该方法允许你接受用户输入作为字符串并将其存储在变量中,如下所示:
const input = prompt();
此方法还接受一个字符串作为附加信息,以了解应用程序需要什么输入。
例如,提示输入用户名的以下代码如下所示:
const input = prompt("What's your name?");
alert(`Your name is ${input}`);
alert()
方法显示结果。你可以根据你的要求将行文本设置为问题或提示。
要接受来自 NodeJS 控制台的用户输入,你必须使用提供的 readline
模块。
你可以从模块中使用以下命令,例如 require()
,如下所示:
const readline = require("readline");
然后你需要实例化附加到输入流的接口。使用 readline.createInterface()
方法创建接口并将输入和输出参数作为对象参数传递。
编写输入和输出需要将输入写入 process.stdin
并输出到 process.stdout
。
这是创建 readline
接口的示例。
const readline = require("readline");
const ql = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
必须在上面代码中分配给 q1
变量的接口实例上调用 question()
方法以请求用户输入。
question()
方法有两个参数。
你可以跳过参数对象并将回调函数作为第二个参数传递。
最后,你可以通过在回调函数中调用 q1.close()
方法来关闭 q1
接口。
arr.js
:
const readline = require("readline");
const q1 = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
q1.question("Where do you live? ", function (answer) {
console.log(`Oh, so you live in ${answer}`);
console.log("Interface Closed");
q1.close();
});
首先,你需要使用 NPM 或 Yarn 安装 prompt-sync
模块,如下所示:
npm install prompt-sync
or
yarn add prompt-sync
然后,你需要 require()
到 prompt-sync
模块。
看看下面的代码。
pm.js
:
const prompt = require("prompt-sync")();
const input = prompt("Where do you live? ");
console.log(`Oh, so you live in ${input}`);
因为此方法是同步的,所以 Node 实例在执行下一行之前等待输入。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。