JavaScript/保留字/函数
外观
< JavaScript | 保留字
thefunction关键字用于开始函数的声明和定义。它可以以两种方式使用:作为
functionName = function(…) { […] };
或者作为
function functionName(…) { […] };
代码
capitalize = function(properName) {
return trim(makeProperName(properName));
};
function makeProperName(noun) {
if (typeof(noun) == 'string') {
if (noun.length > 1) {
chars = noun.split('');
for (i = 0; i < chars.length; i++) {
chars[i] = (i == 0 || chars[i - 1] == ' ')
? chars[i].toUpperCase()
: chars[i].toLowerCase();
}
noun = chars.join('');
}
}
return noun;
};
function trim(words, searchFor) {
if (typeof(words) == 'string') {
if (typeof(searchFor) == 'undefined') {
searchFor = ' '; // Two spaces
}
words = words.trim();
// As long as there are two spaces, do...
while ((index = words.indexOf(searchFor)) > -1) {
words = words.substring(0, index) + words.substring(index + 1);
}
}
return words;
};
var names = ['anton', 'andrew', 'chicago', 'new york'];
for (i = 0; i < names.length; i++) {
console.log("name = '" + capitalize(names[i]) + "'");
}
返回以下内容
result = 3 name = 'Anton' name = 'Andrew' name = 'Chicago' name = 'New York'