JavaScript原型 - 技术访谈

时间:2015-10-17 17:43:16

标签: javascript prototype this

我上周三接受了一次JavaScript采访,但我遇到了其中一个问题。也许你们可以帮我一把吗?

问题是:在原型函数的帮助下,你会如何在驼峰的情况下将这个打印var a和s用于控制台......

  char connectcmd[50]={0};
  sprintf(connectcmd,"AT+CWJAP=\"%s\",\"%s\"",MYSSID,MYPASS);

...所以结果与此相同?

var s = “hello javier”;
var a = “something else”;

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

return capitalize(this); 


};

谢谢!

2 个答案:

答案 0 :(得分:2)

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?

答案 1 :(得分:1)

我会选择这样的东西:

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