上周三,我参加了一次JavaScript面试,其中一个问题我遇到了麻烦。也许你们可以帮我一把?
问题是:如何在原型函数的帮助下将变量a和s打印到控制台,在camel的情况下。
var s = “hello javier”;
var a = “something else”;
String.prototype.toCamelCase = function() {
/* code */
return capitalize(this);
};...so结果和这样做是一样的吗?
console.log(s.toCamelCase());
console.log(a.toCamelCase());
>HelloJavier
>SomethingElse谢谢!
发布于 2015-10-18 01:55:26
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?
发布于 2015-10-18 02:02:39
我会选择这样的方式:
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());https://stackoverflow.com/questions/33189669
复制相似问题