1. 摄氏度转换为华氏度 ```javascript function convertToF(celsius) { let fahrenheit = celsius * 9 / 5 + 32; return fahrenheit; }

convertToF(30);

  1. 2. 反转字符串
  2. ```javascript
  3. // 解法1, 逆序遍历
  4. function reverseString(str) {
  5. let res = '';
  6. for (let i = str.length -1; i >= 0; i--) {
  7. res += str[i]
  8. }
  9. return res;
  10. }
  11. reverseString("hello");
  12. // 解法2, 使用首尾指针,前后对称交换
  13. function reverseString(str) {
  14. let arr = str.split('')
  15. let start = 0, end = arr.length - 1;
  16. while(start < end) {
  17. [arr[end], arr[start]] = [arr[start], arr[end]]
  18. start++;
  19. end--
  20. }
  21. return arr.join('')
  22. }
  23. reverseString("hello");
  24. // 解法三,首尾指针优化,start + end = 2 * mid = length - 1, end = length - 1 - start
  25. function reverseString(str) {
  26. let arr = str.split('')
  27. let start = 0, len = arr.length;
  28. while(start < Math.floor(len / 2)) {
  29. let end = len - 1 - start;
  30. [arr[end], arr[start]] = [arr[start], arr[end]]
  31. start++;
  32. }
  33. return arr.join('')
  34. }
  35. reverseString("hello");
  36. // 解法四,使用数组API, split, reverse, join
  37. function reverseString(str) {
  38. let arr = str.split('')
  39. return arr.reverse().join('')
  40. }
  41. reverseString("hello");
  42. // 解法五, 使用递归,每次交互首尾字符
  43. function reverseString(str) {
  44. if (!str) return ""
  45. if (str.length == 1) return str
  46. let end = str.length - 1
  47. return str[end] + reverseString(str.slice(1,end)) +str[0]
  48. }
  49. reverseString("hello");
  1. 阶乘计算 ```javascript //解法1, 使用迭代 function factorialize(num) { let res = 1; for (let i = 2; i <= num; i++) { res *= i; } return res; }

factorialize(5);

// 解法2, 使用递归 function factorialize(num) { if (num === 0) return 1 return num * factorialize(num - 1) }

factorialize(5);

  1. 4. 寻找字符串中的最长单词长度
  2. ```javascript
  3. // 解法1, 使用遍历,使用res变量记录最终结果,temp记录扫描的每个单词长度
  4. function findLongestWordLength(str) {
  5. let res = 0
  6. let temp = 0;
  7. for (let i = 0; i < str.length; i++) {
  8. if (str[i] === ' ') {
  9. res = Math.max(res, temp)
  10. temp = 0
  11. } else {
  12. temp++
  13. }
  14. }
  15. return Math.max(res, temp)
  16. }
  17. findLongestWordLength("The quick brown fox jumped over the lazy dog");
  18. // 解法2, 把字符串转换成数组处理
  19. function findLongestWordLength(str) {
  20. let arr = str.split(' ')
  21. let res = 0;
  22. for(let i = 0; i < arr.length; i++) {
  23. res = Math.max(res, arr[i].length)
  24. }
  25. return res
  26. }
  27. findLongestWordLength("The quick brown fox jumped over the lazy dog");
  28. // 解法2优化,使用map 和 Math.max,展开运算符
  29. function findLongestWordLength(str) {
  30. return Math.max(...str.split(' ').map(item => item.length))
  31. // 等同于
  32. // return Math.max.apply(null, str.split(' ').map(item => item.length))
  33. }
  34. findLongestWordLength("The quick brown fox jumped over the lazy dog");
  1. 寻找数组中的每一项中的最大值并返回 ```javascript // 解法一,使用for循环迭代 function largestOfFour(arr) { let res = [] for(let i = 0; i < arr.length; i++) { let max = -Infinity; for (let j = 0; j < arr[i].length; j++) { max = Math.max(max, arr[i][j]) } res.push(max) } return res; }

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

// 解法2, 使用数组API function largestOfFour(arr) { return arr.map(subArr => Math.max(…subArr)) } largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

  1. 6. 检查一个字符串是否是目标字符串的末尾子符串
  2. ```javascript
  3. // 解法1,endsWith API
  4. function confirmEnding(str, target) {
  5. return str.endsWith(target)
  6. }
  7. confirmEnding("Bastian", "n");
  8. // 解法2, 使用i,j指针从尾部扫描
  9. function confirmEnding(str, target) {
  10. if (str.length < target.length) return false;
  11. let j = target.length - 1;
  12. let i = str.length - 1;
  13. while(j > -1) {
  14. if (str[i] !== target[j]) {
  15. return false;
  16. }
  17. i--;
  18. j--;
  19. }
  20. return true
  21. }
  22. confirmEnding("Bastian", "n");
  23. // 解法3, 使用slice API
  24. function confirmEnding(str, target) {
  25. if (str.length < target.length) return false;
  26. return str.slice(-target.length) === target;
  27. }
  28. confirmEnding("Bastian", "n");
  29. // 解法4, 使用正则
  30. function confirmEnding(str, target) {
  31. if (str.length < target.length) return false;
  32. return RegExp(target + '$').test(str)
  33. }
  34. confirmEnding("Bastian", "n");
  1. 重复一个字符串 ```javascript // 解法1, 遍历相加 function repeatStringNumTimes(str, num) { let res = ‘’ for (let i = 0; i < num; i++) { res += str } return res; }

repeatStringNumTimes(“abc”, 3); // abcabcabc

// 解法2,利用数组然后join function repeatStringNumTimes(str, num) { if (num <= 0) return ‘’ return Array(num + 1).join(str) }

repeatStringNumTimes(“abc”, 3);

// 解法3, 使用递归 function repeatStringNumTimes(str, num) { if (num <= 0) return ‘’ if (num == 1) return str; return str + repeatStringNumTimes(str, num - 1); }

repeatStringNumTimes(“abc”, 3);

  1. 9. 截取字符串,超出变成 ...
  2. ```javascript
  3. function truncateString(str, num) {
  4. if (str.length > num) {
  5. return str.slice(0, num) + '...'
  6. }
  7. return str;
  8. }
  9. truncateString("A-tisket a-tasket A green and yellow basket", 8);
  1. 遍历数组里每个元素,对数组的每个元素都调用指定的函数,并返回第一个为真的结果的元素,没有返回undefined ```javascript // 解法1, for遍历 function findElement(arr, func) { for(let i = 0; i < arr.length; i++) { if (func(arr[i])) { return arr[i] } } return undefined; }

findElement([1, 2, 3, 4], num => num % 2 === 0);

// 解法2, 使用filter function findElement(arr, func) { return arr.filter(func)[0] }

findElement([1, 2, 3, 4], num => num % 2 === 0);

// 解法3, 使用find function findElement(arr, func) { return arr.find(func) }

findElement([1, 2, 3, 4], num => num % 2 === 0);

  1. 10. 判断值是否为布尔值
  2. ```javascript
  3. // 解法1, 判读为true or false
  4. function booWho(bool) {
  5. return bool === true || bool === false
  6. }
  7. booWho(null);
  8. // 解法2, typeof
  9. function booWho(bool) {
  10. return typeof bool === 'boolean'
  11. }
  12. booWho(null);
  1. 每个单词的首字符大写 ```javascript // 解法1, 遍历 + 标志位 function titleCase(str) { let shouldCap = true; let res = ‘’; for(let i = 0; i < str.length; i++) { if(shouldCap) { res += str[i].toUpperCase() shouldCap = false; } else { res += str[i].toLowerCase() if (str[i] === ‘ ‘) {
    1. shouldCap = true
    } } } return res; }

titleCase(“I’m a little tea pot”);

// 解法2, 转换为数组处理 function titleCase(str) { return str.split(‘ ‘).map(word => { return word[0].toUpperCase() + word.slice(1).toLowerCase() }).join(‘ ‘) }

titleCase(“I’m a little tea pot”);

// 解法3, 使用正则表达式 function titleCase(str) { return str.toLowerCase() .replace(/(^|\s)[a-z]/g, match => match.toUpperCase()) }

titleCase(“I’m a little tea pot”);

  1. 12. 使用数组的slicesplice 方法把一个数组中的元素放在第二个数组的指定索引位置之后,不改变第二个数组
  2. ```javascript
  3. function frankenSplice(arr1, arr2, n) {
  4. let copy = arr2.slice()
  5. copy.splice(n, 0, ...arr1)
  6. return copy
  7. }
  8. frankenSplice([1, 2, 3], [4, 5, 6], 1);
  1. 从一个数组中移除所有的falsy值,falsy = false | null | 0 | ‘’ | undefined | NaN ```javascript // 解法1, 使用数组API function bouncer(arr) { return arr.filter(Boolean) }

bouncer([7, “ate”, “”, false, 9]);

// 解法2 ,遍历 function bouncer(arr) { let res = [] for (let i = 0; i < arr.length; i++) { if (Boolean(arr[i])) { res.push(arr[i]) } } return res }

bouncer([7, “ate”, “”, false, 9]);

  1. 14. 返回数组被插入元素后,再排序后的,该元素的索引
  2. ```javascript
  3. // 例如, getIndexToIns([1,2,3,4], 1.5) // 数组插入1.5,排序后,值的索引为1
  4. // 解法1, 数组排序后使用indexOf返回索引
  5. function getIndexToIns(arr, num) {
  6. return arr.concat(num).sort((a,b)=> a-b).indexOf(num)
  7. }
  8. getIndexToIns([40, 60], 50);
  9. //解法2, 使用filter
  10. function getIndexToIns(arr, num) {
  11. return arr.filter(e => e < num).length
  12. }
  13. getIndexToIns([40, 60], 50);
  14. //解法3, 遍历记数小于num的数量,即为插入的索引值
  15. function getIndexToIns(arr, num) {
  16. let res = 0;
  17. for (let i = 0; i < arr.length; i++) {
  18. if (arr[i] < num) {
  19. res++
  20. }
  21. }
  22. return res
  23. }
  24. getIndexToIns([40, 60], 50);
  1. 第一个字符串是否包含第二字符串中所有字符,不考虑字符的大小写 ```javascript // 解法1, 遍历 function mutation(arr) { let arr1 = arr[0].toLowerCase() let arr2 = arr[1].toLowerCase() for (let i = 0; i < arr2.length; i++) { if (!arr1.includes(arr2[i])) { return false; } } return true }

mutation([“hello”, “hey”]);

// 解法2, 转为数组处理, every; function mutation(arr) { let str1 = arr[0].toLowerCase(); let arr2 = arr[1].toLowerCase().split(‘’); return arr2.every(item => str1.includes(item)) }

mutation([“hello”, “hey”]);

// 解法3,使用set, 时间复杂度O(n) function mutation(arr) { let set = new Set(arr[0].toLowerCase()) for (let char of arr[1].toLowerCase()) { if (!set.has(char)) { return false; } } return true }

mutation([“hello”, “hey”]);

// 解法4, 使用者正则表达式, 第二个字符串有第一个字符串不存在的字符,结果取反 function mutation(arr) { return !RegExp([^${arr[0]}], ‘i’).test(arr[1]) }

mutation([“hello”, “hey”]);

  1. 16. 写一个函数能够按照指定的大小切割原数组,并返回一个二维数组
  2. ```javascript
  3. // 解法1, 遍历 + 临时数组保存,双指针
  4. function chunkArrayInGroups(arr, size) {
  5. let result = []
  6. for (let i = 0; i < arr.length; i+=size) {
  7. let temp = []
  8. for (let j = i; j < i + size && j < arr.length; j++) {
  9. temp.push(arr[j])
  10. }
  11. result.push(temp)
  12. }
  13. return result
  14. }
  15. chunkArrayInGroups(["a", "b", "c", "d"], 2);
  16. // 解法2, 使用mod 取余
  17. function chunkArrayInGroups(arr, size) {
  18. let result = []
  19. let temp = []
  20. for (let i = 0; i < arr.length; i++) {
  21. temp.push(arr[i])
  22. if (i % size === size - 1) {
  23. result.push(temp)
  24. temp = []
  25. }
  26. }
  27. if (temp.length > 0) {
  28. result.push(temp)
  29. }
  30. return result
  31. }
  32. chunkArrayInGroups(["a", "b", "c", "d"], 2);
  33. // 解法3, 使用数组 splice
  34. function chunkArrayInGroups(arr, size) {
  35. let result = []
  36. while(arr.length > 0) {
  37. result.push(arr.splice(0, size))
  38. }
  39. return result;
  40. }
  41. chunkArrayInGroups(["a", "b", "c", "d"], 2);
  42. // 解法4, 使用数组 slice
  43. function chunkArrayInGroups(arr, size) {
  44. let result = []
  45. for(let i = 0; i < arr.length; i += size) {
  46. result.push(arr.slice(i, i + size))
  47. }
  48. return result
  49. }
  50. chunkArrayInGroups(["a", "b", "c", "d"], 2);
  51. // 解法5, 使用数组 reduce
  52. function chunkArrayInGroups(arr, size) {
  53. return arr.reduce((acc, cur) => {
  54. let last = acc[acc.length - 1]
  55. if (last.length < size) {
  56. last.push(cur)
  57. } else {
  58. acc.push([cur])
  59. }
  60. return acc
  61. }, [[]])
  62. }
  63. chunkArrayInGroups(["a", "b", "c", "d"], 2);
  64. // 解法6, 使用递归
  65. function chunkArrayInGroups(arr, size) {
  66. if (arr.length <= size) {
  67. return [arr]
  68. }
  69. return [arr.splice(0, size)]
  70. .concat(chunkArrayInGroups(arr, size))
  71. }
  72. chunkArrayInGroups(["a", "b", "c", "d"], 2);
  73. function chunkArrayInGroups(arr, size) {
  74. if (arr.length <= size) {
  75. return [arr]
  76. }
  77. return [arr.slice(0, size)]
  78. .concat(chunkArrayInGroups(arr.slice(size), size))
  79. }
  80. chunkArrayInGroups(["a", "b", "c", "d"], 2);

参考资料

  1. https://chinese.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#basic-data-structures
  2. https://www.bilibili.com/video/BV1iZ4y1p7kr