javascript - Why is my my prompt for a user name failing while trying to create a system to generate a random code with user initials?
问题描述
I am trying to create a script that can be run in a browser by our school district's secretaries. Basically they will put in a new student or new hires name and get a 8 digit output, a six digit random number and the users initials added at the end. They will be copying this into one of our systems and the unique code will kickstart automatic account creation. We have the account creation set and working, but are having a hard time getting the unique code. I have not included the random number portion of the script as my only problem lies with prompting for the user's name and extracting the initials.
function ID() {
var userName = prompt("Please enter your name", "<User Name>");
}
function getInitials(name) {
let initials = "";
let waitingForSpace = false;
for (var i = 0; i < name.length; i++) {
if (!waitingForSpace) {
initials += name[i];
waitingForSpace = true;
}
if (name[i] === " ") {
waitingForSpace = false;
}
}
return initials;
}
console.log(getInitials(userName));
I think I should get a prompt for User Name, which is stored as userName. That is then used to getInitials. however when I try and run Node Initials.js I get...
ReferenceError: userName is not defined
at Object. (/Users/dross/Documents/UserID/Initials.js:22:25)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js(internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
解决方案
您的代码中缺少一个}
。您可以将代码更改为以下内容:
function getUserName() {
var userName = prompt("Please enter your name", "<User Name>");
return userName; // return the entered name
}
function getInitials(name) {
let initials = "";
let waitingForSpace = false;
for (var i = 0; i < name.length; i++) {
if (!waitingForSpace) {
initials += name[i];
waitingForSpace = true;
}
if (name[i] === " ") {
waitingForSpace = false;
}
}
return initials;
}
var name = getUserName(); // returns the name entered
console.log(getInitials(name));
推荐阅读
- algorithm - 如何创建一个没有两首连续歌曲在同一个键中的歌单
- azure - 使用费率卡 API 估算 Azure 定价?
- sql - 动态选择存储过程输出 (SQL Server)
- cypher - 如何在 jQAssistant 中找到循环依赖的示例实例?
- sql-server - 如何将权限从一个数据库复制到另一个数据库?
- ios - 如何从中央设备(iPhone 7)将布尔值写入外围设备(PSoC BLE)
- reactjs - 反应生命周期方法
- r - 在列名中搜索字符串并检索每一行的相应值
- python - QWidget::setLayout: 试图在已经有布局的 ProgramWindow "" 上设置 QLayout ""
- ajax - f:ajax 不会渲染 h:panelGroup