首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript原型-技术面试

JavaScript原型-技术面试
EN

Stack Overflow用户
提问于 2015-10-18 01:43:16
回答 2查看 332关注 0票数 2

上周三,我参加了一次JavaScript面试,其中一个问题我遇到了麻烦。也许你们可以帮我一把?

问题是:如何在原型函数的帮助下将变量a和s打印到控制台,在camel的情况下。

代码语言:javascript
复制
var s = “hello javier”;
var a = “something else”;

String.prototype.toCamelCase = function() {
/* code */ 

return capitalize(this); 


};

...so结果和这样做是一样的吗?

代码语言:javascript
复制
console.log(s.toCamelCase());
console.log(a.toCamelCase());

>HelloJavier 
>SomethingElse

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2015-10-18 01:55:26

代码语言:javascript
复制
var s = 'hello javier';
var a = 'something else';

String.prototype.toCamelCase = function() {
  return capitalize(this);
};

function capitalize(string) {
  return string.split(' ').map(function(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }).join('');
}
console.log(a.toCamelCase());
console.log(s.toCamelCase());

参考How do I make the first letter of a string uppercase in JavaScript?

票数 2
EN

Stack Overflow用户

发布于 2015-10-18 02:02:39

我会选择这样的方式:

代码语言:javascript
复制
var s = "hello javier";
var a = "something else";

String.prototype.toCamelCase = function() {  
  function capitalize(str){
    var strSplit = str.split(' ');

    // starting the loop at 1 because we don't want
    // to capitalize the first letter
    for (var i = 1; i < strSplit.length; i+=1){
      var item = strSplit[i];

      // we take the substring beginning at character 0 (the first one)
      // and having a length of one (so JUST the first one)
      // and we set that to uppercase.
      // Then we concatenate (add on) the substring beginning at
      // character 1 (the second character). We don't give it a length
      // so we get the rest.
      var capitalized = item.substr(0,1).toUpperCase() + item.substr(1);

      // then we set the value back into the array.
      strSplit[i] = capitalized;
    }
    return strSplit.join('');
  }

  return capitalize(this); 

};

// added for testing output
console.log(s.toCamelCase());
console.log(a.toCamelCase());
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33189669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档