Javascript 连接名字、姓氏和代码

Javascript Concatenate FirstName, LastName and 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;
}

您可以使用substring提取第一个字符:

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

Here is the documentation 对于 String.prototype.substring

您的警报行中没有使用 'str' 的定义..

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

以上应该有效。看起来你在 if 块之后有一个 } 。您可能还应该对用户输入进行更多错误检查,例如,如果用户没有在提示符下输入值,您将得到 undefinedundefined#### 其中 #### 是生成的代码。

替换行

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

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