简体   繁体   English

在 Javascript 控制台中输出姓氏的第一个字母以及两个大写字母的首字母?

[英]Outputting first letter of last name as well as both initials in Uppercase in Javascript console?

I'm a new student and having loads of problems with this exercise.我是一名新学生,在这个练习中遇到了很多问题。 Basically we need to write a function that gets a first and last name from the user (separated by a space) and output it into the console.基本上我们需要编写一个 function 从用户那里获取名字和姓氏(用空格分隔)和 output 到控制台。 We need to write 3 different functions, one to output first letter of first name original case, one first letter of last name original case, and a third output of both initials upper case.我们需要编写 3 个不同的函数,一个是 output 名字首字母大写,一个姓氏首字母大写,第三个 output 两个首字母大写。 I've got the first one down but don't understand the split function well enough to get the other two it's driving me nuts.我已经搞定了第一个,但不明白拆分 function 足以让另外两个让我发疯。 here is what i have thus far:这是我到目前为止所拥有的:

function GetText(promptMessage){
    let x = prompt(promptMessage);
    return x;
}

function Initials(FirstName, LastName){
    text = Firstname.charAt(0);
    return text;
}

text =GetText("Enter your name here");
let Firstname = text;
console.log(Initials(text));

function LastInitial(FirstName, LastName){
    var names = string.split(' ');
    return names;
}
var names;
var LastName = LastInitial(LastName);
console.log(LastName);

I basically have no idea how to write the second function and have just been moving the names around hoping to get it to work lol.我基本上不知道如何编写第二个 function 并且一直在移动名称,希望让它发挥作用,哈哈。 haven't even started the Uppercase one... Please help !!甚至还没有开始大写的...请帮助! thanks so much非常感谢

The split() method returns an array of all the elements so to target the second element just do string.split(' ')[1] split() 方法返回一个包含所有元素的数组,因此要定位第二个元素,只需执行string.split(' ')[1]

Below you can find the full code:您可以在下面找到完整的代码:

    function firstInitial(string) {
        return string.charAt(0);
    }

    function lastInitial(string) {
        return string.split(" ")[1].charAt(0);
    }

    function bothInitials(string) {
        return (firstInitial(string) + lastInitial(string)).toUpperCase();
    }

    let name = prompt("Enter a name");

    console.log(firstInitial(name));
    console.log(lastInitial(name));
    console.log(bothInitials(name));

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

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