简体   繁体   English

Javascript连接名字,姓氏和代码

[英]Javascript Concatenate FirstName, LastName and Code

I am trying to concatenate the first letter of both names onto the randomly generated code. 我试图将两个名称的首字母连接到随机生成的代码上。

   var firstname = prompt("Please enter your first name.");
   var lastname = prompt ("Please enter your last name.");

   if (amountCorrect >= 4){
            alert("Your login Code for the store is: " + str(firstname,1,1) + str(lastname,1,1) + (generateCode())); // Do the generateCode function
        }
        else{
            alert("You have not passed on this occasion. You will now be taken back to the homepage.");
            window.history.go(-1); // Go back a step
        }
    }

    function generateCode(){

    var text        = "";
    var possible    = "0123456789";

    for( var i=0; i < 4; i++ ){
        text += possible.charAt(Math.floor(Math.random() * possible.length));   
    }

    return text;
}

You can use substring to extract the first character: 您可以使用substring提取第一个字符:

alert("Your login Code for the store is: " + firstname.substring(0,1) + lastname.substring(0,1) + (generateCode()));

Here is the documentation for String.prototype.substring . 这是 String.prototype.substring 的文档

There is no definition for 'str' used within your alert line.. 警报行中没有使用“ str”的定义。

alert("Your login Code for the store is: " + firstname[0] + lastname[0] + (generateCode()));

The above should work. 以上应该可以。 It also looks like you have a stray } after the if block. 在if块之后,您似乎也有一个流浪}。 You should probably also be doing more error checking for the user input, if the user doesn't enter a value at the prompt for example, you will get undefinedundefined#### where #### is the generated code. 您可能还应该对用户输入进行更多的错误检查,例如,如果用户未在提示符下输入值,则会得到undefinedundefined ####,其中####是生成的代码。

Replace the line 更换线

alert("Your login Code for the store is: " + str(firstname,1,1) + str(lastname,1,1) + (generateCode())); // Do the generateCode function

with

alert("Your login Code for the store is: " + firstname.substring(1, 0) + lastname.substring(1, 0) + (generateCode())); // Do the generateCode function

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

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