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'