首页 > 解决方案 > 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)

标签: javascript

解决方案


您的代码中缺少一个}。您可以将代码更改为以下内容:

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));


推荐阅读