簡體   English   中英

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

這是 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM