返回

成为 Typescript 高手,从这 10 篇文章开始!

前端


前言

欢迎来到搞定 Typescript 系列的第十篇文章!如果你是一位想要从零开始学习 Typescript 的新手,那么强烈建议你从第一篇开始阅读,以便更好地理解后续内容。

第一题
很简单的一道入门题:

function sum(a: number, b: number): number {
  return a + b;
}

这个函数接受两个数字作为参数,并返回它们的和。

console.log(sum(1, 2)); // 3
console.log(sum(3, 4)); // 7

第二题
这道题稍微有点难度,它要求我们实现一个函数,该函数接受一个数组作为参数,并返回数组中最大值和最小值。

function findMinMax(arr: number[]): { max: number; min: number } {
  let max = arr[0];
  let min = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
    if (arr[i] < min) {
      min = arr[i];
    }
  }
  return { max, min };
}

console.log(findMinMax([1, 2, 3, 4, 5])); // { max: 5, min: 1 }
console.log(findMinMax([9, 2, 5, 7, 1])); // { max: 9, min: 1 }

第三题
这道题要求我们实现一个函数,该函数接受一个字符串作为参数,并返回一个包含该字符串中所有元音字母的新字符串。

function getVowels(str: string): string {
  const vowels = "aeiouAEIOU";
  let result = "";
  for (let i = 0; i < str.length; i++) {
    if (vowels.includes(str[i])) {
      result += str[i];
    }
  }
  return result;
}

console.log(getVowels("Hello World")); // "eoo"
console.log(getVowels("The Quick Brown Fox")); // "ueio"

第四题
这道题要求我们实现一个函数,该函数接受一个字符串作为参数,并返回一个包含该字符串中所有辅音字母的新字符串。

function getConsonants(str: string): string {
  const consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
  let result = "";
  for (let i = 0; i < str.length; i++) {
    if (consonants.includes(str[i])) {
      result += str[i];
    }
  }
  return result;
}

console.log(getConsonants("Hello World")); // "llWrld"
console.log(getConsonants("The Quick Brown Fox")); // "ThQckBrwnFx"

第五题
这道题要求我们实现一个函数,该函数接受一个数字作为参数,并返回该数字的阶乘。

function factorial(num: number): number {
  if (num === 0) {
    return 1;
  }
  return num * factorial(num - 1);
}

console.log(factorial(5)); // 120
console.log(factorial(10)); // 3628800

总结

以上就是搞定 Typescript 系列的第十篇文章,希望对你有所帮助。如果你想了解更多关于 Typescript 的知识,欢迎继续关注我的后续文章。