简体   繁体   English

有没有办法将 firstName 和 lastName 的第一个字母大写并使其成为 Javascript 中的首字母

[英]Is there a way to Capitalize the first letter of firstName and lastName and make it an Innitial in Javascript

// Add a method to the Person's prototype called "getInitials" that returns the first letter of their first and last name, both capitalized. // 向 Person 的原型添加一个名为“getInitials”的方法,该方法返回他们的名字和姓氏的第一个字母,都大写。

 function Person(firstName, lastName) { Person.prototype.getInitials = function() { let name = (firstName, lastName) => { return name.split(' ').map(word => word.substr(0, 1).toUpperCase() + word.substr(1, word.length)).join(' '); }; } } /* Do not modify code below this line */ const johnDoe = new Person('john', 'doe'); console.log(johnDoe.getInitials(), '<-- should be "JD"');

  1. Do not set the prototype inside Person 's constructor不要在Person的构造函数中设置原型

Every time you instantiate a Person you will modify the prototype of Person which is not what you want to do.每次实例化Person时,您都会修改Person的原型,这不是您想要做的。 Set it once (outside of Person ) is enough.设置一次(在Person之外)就足够了。

  1. You don't need to substring everything, just keep the first letter您不需要 substring 一切,只需保留第一个字母

 function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } Person.prototype.getInitials = function() { return `"${(this.firstName[0]+this.lastName[0]).toUpperCase()}"`; } /* Do not modify code below this line */ const johnDoe = new Person('john', 'doe'); console.log(johnDoe.getInitials(), '<-- should be "JD"');

Can't it be like this below, isn't it easier?不能像下面这样,不是更简单吗?

You don't need to define prototype inside the Person , but can use this .您不需要在Person内部定义原型,但可以使用this Also you can just get the first character by index position [0] , without splits or substrings.您也可以通过索引 position [0]获取第一个字符,无需拆分或子字符串。

 function Person(firstName, lastName) { this.getInitials = function() { return firstName[0].toUpperCase() + lastName[0].toUpperCase() }; } const johnDoe = new Person('john', 'doe'); console.log(johnDoe.getInitials()); const maryAnn = new Person('mary', 'ann'); console.log(maryAnn.getInitials());

Of course, I would recommend some verification to see if firstName and lastName aren't null/undefined before get its first character.当然,我建议在获取第一个字符之前进行一些验证,以查看firstNamelastName是否不为空/未定义。

If you want to define prototype, then do it outside of Person如果要定义原型,请在Person之外进行

function Person(f,n){...};
Person.prototype.getInitials = function(){...}

 var firstName ="jhon"; var lastName = "doe"; getInitials= function(fname,lname){ return fname[0].toUpperCase()+' '+lname[0].toUpperCase(); } console.log(getInitials(firstName,lastName));

YOu can do something like using classes你可以做一些事情,比如使用类

 class Person { constructor (firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } getInitials () { return this.firstName[0].toUpperCase() + this.lastName[0].toUpperCase(); } } const person = new Person('jon', 'doe'); console.log(person.getInitials());

Answer:回答:

To do what you're trying to do we can hardcode getInitials as a method on our Person Constructor:为了做你想做的事情,我们可以将getInitials硬编码为 Person 构造函数上的一个方法:

// Construct Object
function Person(firstName, lastName) {
  return Object.assign(this, { firstName, lastName });
}

// adjust Constructor Prototype
Person.prototype.getInitials = function() {
         return `${this.firstName[0]} ${this.lastName[0]}`.toUpperCase();
}

 // Construct Object function Person(firstName, lastName) { return Object.assign(this, { firstName, lastName }); } // adjust Constructor Prototype Person.prototype.getInitials = function() { return `${this.firstName[0]} ${this.lastName[0]}`.toUpperCase(); } /* Do not modify code below this line */ const johnDoe = new Person('john', 'doe'); console.log( johnDoe.getInitials() )


Alternatives:备择方案:

In cases like this it's often beneficial to keep in line the idea that methods are actions instead of property seeking .在这种情况下,保持methods操作而不是属性搜索的想法通常是有益的。

For instance, instead of equipping your constructed Object with something like Person.getInitials it would make more sense, logically, to be able to simply write Person.initials .例如,与其为您构造的 Object 配备诸如Person.getInitials之类的东西,从逻辑上讲,能够简单地编写Person.initials会更有意义。

In keeping with that we can choose to hardcode the property:为此,我们可以选择对属性进行硬编码:

function Person(firstName, lastName) {
  return Object.assign(this, {
    firstName,
    lastName,
    initials: `${firstName[0]} ${lastName[0]}`.toUpperCase()
  })
}

 function Person(firstName, lastName) { return Object.assign(this, { firstName, lastName, initials: `${firstName[0]} ${lastName[0]}`.toUpperCase() }) } /* Do not modify code below this line */ const johnDoe = new Person('john', 'doe'); console.log(johnDoe.initials)

Or, if we're looking to be more clear with our code ( always a good thing ), we could do the following utilizing an accessor property ( otherwise known as getters and/or setters ):或者,如果我们希望代码更清晰(总是一件好事),我们可以使用访问器属性(也称为getters和/或setters )执行以下操作:

function Person(firstName, lastName) {

  // define properties
  Object.defineProperties(this, {
    firstName: {
      value: firstName
    },
    lastName: {
      value: lastName
    },
    initials: {
      get: function() {
        return `${firstName[0]} ${lastName[0]}`.toUpperCase();
      }
    }
  });

}

 function Person(firstName, lastName) { // define properties Object.defineProperties(this, { firstName: { value: firstName }, lastName: { value: lastName }, initials: { get: function() { return `${firstName[0]} ${lastName[0]}`.toUpperCase(); } } }); } /* Do not modify code below this line */ const johnDoe = new Person('john', 'doe'); console.log( johnDoe.initials )


Aside:在旁边:

An additional benefit of not extending the prototype unnecessarily is that you are able to prevent changes to these Constructed Objects by freezing them when they are created.不不必要地扩展prototype的另一个好处是,您可以通过在创建这些构造对象时冻结它们来防止对它们进行更改。 This adds some peace-of-mind if, in the future, some other Developer tries to alter the Object on the fly instead of altering the Constructor properly.如果将来有其他开发人员尝试即时更改 Object 而不是正确更改构造函数,这会增加一些安心。 This also doubles as a, albeit flimsy, piece of extra security for your code.这也可以兼作代码的额外安全性,尽管很脆弱。

function Person(firstName, lastName) {

  // define properties
  Object.defineProperties(this, {
    firstName: {
      value: firstName
    },
    lastName: {
      value: lastName
    },
    initials: {
      get: function() {
        return `${firstName[0]} ${lastName[0]}`.toUpperCase();
      }
    }
  });

  // prevent alteration
  Object.freeze(this);

}

 function Person(firstName, lastName) { // define properties Object.defineProperties(this, { firstName: { value: firstName }, lastName: { value: lastName }, initials: { get: function() { return `${firstName[0]} ${lastName[0]}`.toUpperCase(); } } }); // prevent alteration Object.freeze(this); } /* Do not modify code below this line */ const johnDoe = new Person('john', 'doe'); console.log(johnDoe.initials) console.log("Attempting to change firstName to Zak..."); johnDoe.firstName = "Zak"; console.log("But firstName remains: " + johnDoe.firstName);


Conclusion:结论:

Though ultimately everything is entirely open to your circumstances and discretion, I hope this answer helps illuminate some of the different options you have to produce clearer and more efficient code!尽管最终一切都完全取决于您的情况和自由裁量权,但我希望这个答案有助于阐明您必须使用一些不同的选项来生成更清晰、更高效的代码!

Happy Coding!快乐编码!

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

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