简体   繁体   中英

Call a function in another funtion

I want to get the first name of a customer and use that in other functions.

I have an address:

John Doe Streetname 1 1234AA Village

 function firstName(){ let address = "John Doe\nStreetname 1\n 1234AA Village"; let firstname = adres.split(' ')[0]; } function customerText(){ firstName(); let text = "Dear "+firstname+", how is life?"; alert(text); }

So that the result would be: Dear John, how is life?

But unfortunately, it doesn't. Don't know how this should work?

return the firstname and use it in the second function

 function firstName(){ let address = "John Doe\nStreetname 1\n 1234AA Village"; let firstname = address.split(' ')[0]; return firstname; } function customerText(){ let text = "Dear "+firstName()+", how is life?"; alert(text); } // call your function customerText();

OR pass firstname as parameter to the second function

 function firstName(){ let address = "John Doe\nStreetname 1\n 1234AA Village"; let firstname = address.split(' ')[0]; customerText(firstname); } function customerText(nameParameter){ let text = "Dear "+nameParameter+", how is life?"; alert(text); } // call your function firstName();

Here is the modified code: I hope this will help you.

 function firstName() { let address = "John Doe\nStreetname 1\n 1234AA Village"; let firstname = address.split(' ')[0]; customerText(firstname) } function customerText(fname) { let text = "Dear " + fname + ", how is life?"; alert(text); } firstName()

You can get the return value of the fName() in customerText() function and put it right into the text.

 function fName(){ return 'Robert' } function customerText(){ return `Hi, ${fName()}, how are you:)?` } console.log(customerText())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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