JavaScript 专项练习:函数篇(一)

引言

在学习 JavaScript 的过程当中看了很多书,但却不多有专项练习,所以开这样一个专题,但愿能在练习中复习巩固所学的知识~ :)web

函数篇(一)

本篇主要考察编写函数的技能和基本知识,同时也是对 JavaScript 标准库函数的练习。函数

1. 写一个函数用来反转数字学习

reverseNumber(12345); // 54321

2. 写一个函数来检测传入的字符串是否为回文ui

isPalindrome('hello'); // false
isPalindrome('madam'); // true

3. 写一个函数对传入的字符串输出全部子字符串组合(注意去重)code

substrings('dog'); // ['d', 'do', 'dog', 'o', 'og', 'g']

4. 写一个函数对传入的字符串从新按字母排序排序

reorderStr('webmaster'); // abeemrstw

5. 写一个函数对传入的字符串中每一个单词的首字母大写ip

upperWords('the quick brown fox'); // The Quick Brown Fox

6. 写一个函数找出传入的字符串中最长的单词字符串

findLongest('Web Development Tutorial'); // Development

答案

如下给出个人解法,期待能有更好的答案。get

// 1. 写一个函数用来反转数字

(function(){
  'use strict';
  function reverseNumber(num) {
    if(typeof num !== 'number') {
      throw "Pls input a number!";
    }
    var result = num.toString().split('').reverse().join('');
    return +result;
  }
  
  console.log(reverseNumber(12345));
})();
// 2. 写一个函数来检测传入的字符串是否为回文

(function(){
  'use strict';
  function isPalindrome(str) {
    if(typeof str !== 'string') {
      throw "Pls input a string!";
    }
    var tmp = str.split('').reverse().join('');
    return tmp === str;
  }
  
  console.log(isPalindrome('hello'));
  console.log(isPalindrome('madam'));
})();
// 3. 写一个函数对传入的字符串输出全部子字符串组合

(function(){
  'use strict';
  function substrings(str) {
    if(typeof str !== 'string') {
      throw "Pls input a string!";
    }
    var result = [];
    function next(idx) {
      var i, n = str.length - idx;
      for(i=1; i<=n; i++) {
        add(str.substr(idx, i));
      }
      if(idx < str.length){
        next(idx+1);
      }
    }
    function add(item) {
      if(result.indexOf(item)<0) {
        result.push(item);
      }
    }
    next(0);
    return result;
  }
  
  console.log(substrings('dog'));
})();
// 4. 写一个函数对传入的字符串从新按字母排序

(function(){
  'use strict';
  function reorderStr(str) {
    if(typeof str !== 'string') {
      throw "Pls input a string!";
    }
    return str.split('').sort().join('');
  }
  
  console.log(reorderStr('webmaster'));
})();
// 5. 写一个函数对传入的字符串中每一个单词的首字母大写

(function(){
  'use strict';
  function upperWords(str) {
    if(typeof str !== 'string') {
      throw "Pls input a string!";
    }
    return str.split(' ').map(upperFirstLetter).join(' ');
    
    function upperFirstLetter(str) {
      return str.charAt(0).toUpperCase().concat(str.substr(1));
    }
  }
  
  console.log(upperWords('the quick brown fox'));
})();
// 6. 写一个函数找出传入的字符串中最长的单词

(function(){
  'use strict';
  function findLongest(str) {
    if(typeof str !== 'string') {
      throw "Pls input a string!";
    }
    var items = str.split(' ');
    return getMax(items);
    
    function getMax(arr) {
      var i, max = 0, n=arr.length;
      for(i = 0; i < n; i++) {
        if(arr[i].length > arr[max].length) {
          max = i;
        }
      }
      return arr[max];
    }
  }
  
  console.log(findLongest('Web Development Tutorial'));
})();
相关文章
相关标签/搜索