跳轉到內容

JavaScript/保留字/函式

來自華夏公益教科書,自由的教科書
上一個:for 保留字 下一個:goto

thefunction關鍵字

[編輯 | 編輯原始碼]

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'


另請參見

[編輯 | 編輯原始碼]
上一個:for 保留字 下一個:goto
華夏公益教科書