30 个最佳 JavaScript 面试热身练习

2025-05-27

30 个最佳 JavaScript 面试热身练习

阅读 CodeThat.today 上的原文

很多时候,当我们即将进行面试时,你会被要求在面试官面前用你选择的语言完成一项技术任务。因为这个阶段对你的成功至关重要,所以做好准备,至少要对你的编程技能更有信心,这一点很重要。

因此,本文将列出 JavaScript 面试中最重要的热身练习。这些练习都是一些简单的基础问题,要求你编写一个简单的函数,并在必要时进一步扩展。

这并非完整的面试准备,因为面试官可能会问更高级的问题。不过,这些问题足以拓展你的记忆力。

好了,开始吧。30 个 JavaScript 面试热身练习。本部分列出了 30 个问题中的前 10 个

问题🤔

以下是完整的算法列表及其详细解释:

  • 1. 编写一个函数来反转字符串

JavaScript 没有内置的 String Builder 类,因此无法修改现有字符串。我们可以做的是创建一个列表,其中包含push原始字符串中从末尾开始的每个字符。

然后我们使用Array Join将字符组合为反转字符串。

代码要点如下:

function reverseString(s) { // Create the result list const result = []; // Start from the end of the string and iterate towards the start for (let i = s.length-1; i >= 0; i -= 1) { // Push the current char in the list result.push(s[i]); } // Combine the result in a string return result.join(''); } // Examples console.log(reverseString("")) console.log(reverseString("abc")) console.log(reverseString("aaabbbcccd"))
  • 2. 编写一个函数从列表中过滤掉数字

我们可以过滤列表并删除所有非数字的内容。那么如何检查列表项是否不是数字呢?如果我们使用 typeOf 运算符,我们可以得到:

typeof 1 // number

但如果面试官询问有效数字和字符串是否也允许,我们会得到:

typeof "1" // string

这不是我们想要的。解决方案是使用isNaN函数。

然而,如果你注意到(也许面试官很挑剔),有两种情况会导致失败:

isNaN('') //false
isNaN(true) //false
isNaN(null) // false
Enter fullscreen mode Exit fullscreen mode

因此,我们要添加三个检查:空字符串、布尔值和空值:

function isBoolean(value) {
  return typeof value === 'boolean';
}

function isEmptyString(value) {
  return typeof value === 'string' && value.trim().length === 0;
}

Enter fullscreen mode Exit fullscreen mode

代码要点如下:

function filterNumbers(arr) { // Create the result list const result = arr.filter(function(value, i) { // Filter based on the rules for checking the input is number if (isNaN(value) || isBoolean(value) || isEmptyString(value) || value === null) { return false; } return true; }); // Return numbers only list return result; } function isBoolean(value) { return typeof value === 'boolean'; } function isEmptyString(value) { return typeof value === 'string' && value.trim().length === 0; } console.log(filterNumbers([1, "2", " ", NaN, Number.POSITIVE_INFINITY, 66, "ab1", false, null]))
  • 3. 编写一个函数来查找未排序列表中的元素。

这是一个典型的线性搜索算法,需要Θ(n)时间才能完成。我们需要遍历整个列表,并将搜索项与当前项进行比较:

function linearSearch(arr, x) { let lo = 0; let hi = arr.length-1; // Iterate from start until the end of list while (lo <= hi) { // If item was found then return index if (arr[lo] === x) { return lo; } else { lo += 1 } } // Return -1 to denote the item was not found return -1; } let arr = [1,3,5,7,9,11,14,18,22]; console.info("Item was found at index: " + linearSearch(arr, 22));
  • 4. 编写一个函数来展示闭包的用法。

请查看 dev.to 上关于什么Closure 的文章。它们更能解释细节。

这是一个简单的例子:

function multiplier(first) { let a = first; return function(b) { return a * b; }; } let multiplyBy2 = multiplier(2); console.info(multiplyBy2(4)); console.info(multiplyBy2(5));

您应该能够解释那里的封闭之处。

  • 5. 什么是 Promise?编写一个返回 Promise 的函数。

请查看 dev.to 上关于什么Promise的文章。它们更能解释细节。

这是一个简单的 Promise 示例:

const resultPromise = function(idea) { return new Promise(function(resolve, reject) { if (idea.isGood) { resolve(idea); } else { reject({ idea: idea, reason: "Not Realistic" }); } }); }; resultPromise({idea: "Make Gold from Iron", isGood: false}) .then(function() { console.info("I'm Rich!") }, function(err) { console.info("Rejected as: " + err.reason); });
  • 6. 编写一个函数来展平项目列表。

这是一道典型的面试题。一个列表可以展平,使其只包含一层项目。例如:[1, [2,3, [4]]]应该展平为[1, 2, 3, 4]

为了扁平化,我们需要递归,因为我们的列表可能层次很深。首先,我们创建结果列表。然后,我们遍历所有项,并检查该项是否为列表。如果不是列表,则将其附加到结果中。否则,我们再次调用调用函数,但使用项的内容。

代码要点如下:

function flatten(arr=[]) { // Create the result list; let result = []; for (let item of arr) { // If item is an array we concat the contents if (Array.isArray(item)) { result = result.concat(flatten(item)); } else { result = result.concat(item); } } return result; } console.info(flatten([[1, 2, [3]], 4]));
  • 7. 编写一个函数来查找排序列表中的元素。

这道题旨在测试你在这里实现二分查找的能力。通过二分查找,你找到中间元素,然后检查它是否是目标元素。如果它小于目标元素,那么我们就知道它位于输入数组的前半部分。如果它大于目标元素,那么它位于输入数组的后半部分。

完整代码如下:

function binarySearch(arr, x) { let lo = 0; let hi = arr.length-1; while (lo <= hi) { // Find mid element let m = Math.floor((lo + hi) / 2); // Check if equal to target if (arr[m] === x) { return m; // Reduce array search space by half } else if (arr[m] < x) { lo = m + 1; } else { hi = m - 1; } } // Item not found return -1; } let arr = [1,3,5,7,9,11,14,18,22]; console.info(console.info("Item was found at index: " + binarySearch(arr, 22)));
  • 8. 编写一个函数,接受两个数字a和,并返回和的b除法以及的模abab

这很简单。这里我们需要返回两个值:

a / ba % b

function divMod(a, b) { // Be careful for division by zero if (b !== 0 ) { return [a / b, a % b]; } return [0, 0]; } console.info(divMod(16, 5)); console.info(divMod(20, 0));
  • 9. 编写一个函数计算 N 的斐波那契数。

在斐波那契数列中,每个元素都是前两项之和。例如,从 0 和 1 开始:

0, 1, 1, 2, 3, 5, 8, ...
Enter fullscreen mode Exit fullscreen mode

我们可以使用递归或 while 循环来实现这一点。使用递归时,我们可能会陷入陷阱,并像这样操作:

function fib(n) {
  if (n === 0) {
    return 0;
  } else if (n === 1) {
    return 1;
  } else {
    return fib(n-1) + fib(n-2);
  }
}
Enter fullscreen mode Exit fullscreen mode

面试官可能会问为什么效率这么低。或者我们可以添加一个记忆功能,让它稍微好一点:

function memo(func) { let cache = {}; return function (x) { if (x in cache) return cache[x]; return cache[x] = func(x); }; }; let fib = memo(function(n) { if (n === 0) { return 0; } else if (n === 1) { return 1; } else { return fib(n-1) + fib(n-2); } }); console.info(fib(20))
  • 10. 编写一个函数,接受一个字符串并返回一个包含字符串字符频率的映射。

要计算频率,我们需要使用哈希表。通常,我们会使用将键映射到值的对象,或者更语义化地使用 JavaScript Map。

我们遍历字符串的所有字符并增加它们的字符计数器。

以下是其代码:

function computeFrequency(s) { // Create the freq hashtable const freqTable = new Map(); // for each char in the string for (ch of s) { // Check if we have seen it already if (!freqTable.has(ch)) { freqTable.set(ch, 1); } else { // Just increase the existing entry freqTable.set(ch, freqTable.get(ch) + 1); } } // Return result return freqTable; } console.info(computeFrequency("abrakatabra"));

下一步

请继续关注下一部分!

😉👌💖

对指导或培训感兴趣吗?

请通过www.techway.io与我联系以获取更多信息。

文章来源:https://dev.to/theodesp/top-30-javascript-interview-warmup-exercises-3174
PREV
30 个最佳 JavaScript 面试热身练习(第 2 部分)
NEXT
面向学生开发者的五大付费开源项目