javascript面试_如何克服5个常见JavaScript面试挑战

javascript面试

The ways tech interviews are being carried out has been at the center of much controversy for a while now. It’s a sensitive topic, especially when it comes to coding challenges.

一段时间以来, 技术面试的方式一直是许多争议的中心。 这是一个敏感的主题,尤其是在涉及编码挑战时。

Not all companies use the same screening process, but for the most part, expect to be asked to solve a coding challenge, either on a suitable platform or on the dreaded whiteboard.

并非所有公司都使用相同的筛选过程,但是在大多数情况下,期望在合适的平台上或可怕的白板上被要求解决编码难题。

One complaint that’s usually made against coding challenges is that they’re mostly irrelevant to the day-to-day tasks the actual job requires. Especially when it comes to front-end interview questions, sometimes it’s curious how what’s missing in the interview are just front-end-related questions on things like browser compatibility, layout methods and DOM events. While this can be true, those who favor this approach and are responsible for hiring in these companies often say something like this:

通常针对编码挑战的一个抱怨是,它们与实际工作所需的日常任务几乎无关。 尤其是涉及前端面试问题时,有时会好奇面试中缺少的内容仅仅是与前端相关的问题,例如浏览器兼容性,布局方法和DOM事件。 尽管这是事实,但那些赞成这种方法并负责在这些公司中招聘人员的人经常说出这样的话:

I’d rather hire a smart person and teach them X than hire someone who knows everything about X but lacks creativity, logic, and reasoning. — Interviewing as a Front-End Engineer in San Francisco

我宁愿雇用一个聪明的人并教给他们X,而不是雇用一个对X有所了解但缺乏创造力,逻辑和推理能力的人。 — 在旧金山作为前端工程师进行面试

Whatever we feel about the way candidates are screened for dev jobs, at the time of writing, coding challenges are still a big part of the interview process.

无论我们对应聘者筛选开发人员工作的方式有何看法,在撰写本文时,编码挑战仍然是面试过程中的重要部分。

In this article, I’m going to show how you can tackle five common coding challenges you might be asked when interviewing for a JavaScript or front-end Junior Developer position. They’re not among the hardest ones you could come across in the interview process, but the way you approach each of them could make the difference between success and failure.

在本文中,我将展示如何在面试JavaScript或前端Junior Developer职位时可能遇到的五个常见编码挑战。 他们并不是您在面试过程中遇到的最困难的人,但是您对待每个人的方式可能会在成功和失败之间有所作为。

技术面试中应对编码挑战的指针 (Pointers on Tackling Coding Challenges for Your Tech Interview)

Before diving into the challenges, let’s go through some tips about how you could approach your tech interview.

在探究挑战之前,让我们先了解一些有关如何进行技术面试的技巧。

  • Put in the time to prepare. Make your priority to research, learn less familiar topics, and practice a lot. If you haven’t got a Computer Science background, make sure you get familiar with some fundamental topics related to algorithms and data structures. There are online platforms, both free and paid, that offer great ways to practice your interview skills. GeeksforGeeks, Pramp, Interviewing.io, and CodeSignal are just a few of my favorite resources.

    投入时间准备 。 优先研究,学习不太熟悉的主题并进行大量练习。 如果您没有计算机科学的背景知识,请确保您熟悉与算法和数据结构有关的一些基本主题。 有免费和付费的在线平台,它们提供了练习面试技巧的好方法。 GeeksforGeeksPrampInterviewing.ioCodeSignal只是我最喜欢的一些资源。

  • Practice thinking aloud when you’re trying to come up with a solution. In fact, talking through your thought process in an interview setting is preferable to spending all the available time writing down your solution in total silence. Your words will give the interviewer a chance to help you if you’re about to take a wrong turn. It also highlights your communication skills.

    尝试提出解决方案时,请练习大声思考 。 实际上,在面试环境中讨论您的思维过程比花所有可用时间写下您的解决方案完全沉默的做法更为可取。 如果您要走错路,您的话语将使面试官有机会帮助您。 它还强调您的沟通技巧。

  • Understand the problem before starting to code. This is important. Otherwise, you might be wasting time thinking about the wrong problem. Also, it forces you to think about questions you may ask your interviewer, like edge cases, the data type of inputs/outputs, etc.

    开始编码之前,请先了解问题 。 这个很重要。 否则,您可能会浪费时间思考错误的问题。 此外,它还会迫使您考虑可能会询问面试官的问题,例如边际案例,输入/输出的数据类型等。

  • Practice writing code by hand. This helps you get familiar with the whiteboard scenario. A whiteboard doesn’t provide the kind of help that your code editor provides — such as shortcuts, autocomplete, formatting, and so on. When preparing, try writing down your code on a piece of paper or on a whiteboard instead of thinking it all up in your head.

    练习手工编写代码 。 这可以帮助您熟悉白板方案。 白板无法提供代码编辑器提供的那种帮助,例如快捷方式,自动完成,格式化等。 准备时,请尝试将代码写在纸上或白板上,而不要全盘考虑。

常见JavaScript编码挑战 (Common Coding JavaScript Challenges)

It’s likely that you’ve come across one or more of the challenges I’ve listed below, either during a job interview or while practicing your JavaScript skills. What better reason is there for getting really good at solving them?

在工作面试期间或在练习JavaScript技能时,您可能遇到了我在下面列出的一个或多个挑战。 有什么更好的理由真正善于解决问题?

Let’s get cracking!

让我们开始吧!

#1回文 (#1 Palindrome)

A palindrome is a word, sentence or other type of character sequence which reads the same backward as forward. For example, “racecar” and “Anna” are palindromes. “Table” and “John” aren’t palindromes, because they don’t read the same from left to right and from right to left.

回文词是单词,句子或其他类型的字符序列,其顺序与后向相同。 例如,“赛车”和“安娜”是回文。 “表格”和“约翰”不是回文,因为它们从左到右和从右到左读的都不同。

了解挑战 (Understanding the challenge)

The problem can be stated along the following lines: given a string, return true if the string is a palindrome and false if it isn’t. Include spaces and punctuation in deciding if the string is a palindrome. For example:

可以按照以下几行说明该问题:给定一个字符串,如果该字符串是回文,则返回true,否则返回false。 在确定字符串是否是回文字符串时,请包含空格和标点符号。 例如:

palindrome('racecar')  ===  true
palindrome('table')  ===  false
关于挑战的推理 (Reasoning about the challenge)

This challenge revolves around the idea of reversing a string. If the reversed string is the same as the original input string, then you have a palindrome and your function should return true. Conversely, if the reversed string isn’t the same as the original input string, the latter is not a palindrome and your function is expected to return false.

这个挑战围绕着反转弦的想法。 如果反转的字符串与原始输入字符串相同,则说明您有回文,并且您的函数应返回true。 相反,如果反向字符串与原始输入字符串不同,则后者不是回文,并且您的函数应返回false。

(Solution)

Here’s one way you can solve the palindrome challenge:

这是解决回文挑战的一种方法:

const palindrome = str => {
  // turn the string to lowercase
  str = str.toLowerCase()
  // reverse input string and return the result of the
  // comparisong
  return str === str.split('').reverse().join('')
}

Start by turning your input string into lower case letters. Since you know you’re going to compare each character in this string to each corresponding character in the reversed string, having all the characters either in lower or upper case will ensure the comparison will leave out this aspect of the characters and just focus on the characters themselves.

首先将输入字符串转换为小写字母。 由于您知道要将该字符串中的每个字符与反向字符串中的每个对应字符进行比较,因此,将所有字符都以小写或大写形式进行比较,将确保比较不会涉及字符的这一方面,而只关注于角色本身。

Next, reverse the input string. You can do so by turning the string into an array using the String’s .split() method, then applying the Array’s .reverse() method and finally turning the reversed array back into a string with the Array’s .join() method. I’ve chained all these methods above so the code looks cleaner.

接下来,反转输入字符串。 您可以使用String的.split()方法将字符串转换为数组,然后应用Array的.reverse()方法,最后使用Array的.join()方法将反向数组转换回字符串,以实现此目的。 我已经在上面链接了所有这些方法,因此代码看起来更简洁。

Finally, compare the reversed string with the original input and return the result — which will be true or false according to whether the two are exactly the same or not.

最后,将反向字符串与原始输入进行比较,然后返回结果-根据两者是否完全相同,结果为true或false。

#2 FizzBu​​zz (#2 FizzBuzz)

This is a super popular coding challenge — the one question I couldn’t possibly leave out. Here’s how you can state the problem.

这是一个超级流行的编码挑战,这是我无法忽略的一个问题。 这是解决问题的方法。

了解挑战 (Understanding the challenge)

The FizzBuzz challenge goes something like this. Write a function that does the following:

FizzBu​​zz挑战是这样的。 编写一个执行以下操作的函数:

  • console logs the numbers from 1 to n, where n is the integer the function takes as its parameter

    控制台记录从1到n的数字,其中n是该函数作为其参数的整数
  • logs fizz instead of the number for multiples of 3

    记录嘶嘶声,而不是数字的3的倍数

  • logs buzz instead of the number for multiples of 5

    记录蜂鸣声,而不是5的倍数的数字

  • logs fizzbuzz for numbers that are multiples of both 3 and 5

    fizzbuzz记录为3和5的倍数的数字

Example:

例:

fizzBuzz(5)

Result:

结果:

// 1
// 2
// fizz
// 4
// buzz
关于挑战的推理 (Reasoning about the challenge)

One important point about FizzBuzz relates to how you can find multiples of a number in JavaScript. You do this using the modulo or remainder operator, which looks like this: %. This operator returns the remainder after a division between two numbers. A remainder of 0 indicates that the first number is a multiple of the second number:

关于FizzBu​​zz的重要一点涉及如何在JavaScript中找到数字的倍数。 您可以使用模或余数运算符执行此操作 ,该运算符如下所示: % 。 在两个数字相除之后,该运算符返回余数。 余数0表示第一个数字是第二个数字的倍数:

12 % 5 // 2 -> 12 is not a multiple of 5
12 % 3 // 0 -> 12 is multiple of 3

If you divide 12 by 5, the result is 2 with a remainder of 2. If you divide 12 by 3, the result is 4 with a remainder of 0. In the first example, 12 is not a multiple of 5, while in the second example, 12 is a multiple of 3.

如果将12除以5,则结果为2,其余数为2。如果将12除以3,则结果为4,其余数为0。在第一个示例中,12不是5的倍数,而在第二个例子,12是3的倍数。

With this information, cracking FizzBuzz is a matter of using the appropriate conditional logic that will lead to printing the expected output.

有了这些信息,破解FizzBu​​zz就是使用适当的条件逻辑来完成,该条件逻辑将导致打印预期的输出。

(Solution)

Here’s one solution you can try out for the FizzBuzz challenge:

您可以尝试以下一种解决方案来应对FizzBu​​zz挑战:

const fizzBuzz = num => {
  for(let i = 1; i <= num; i++) {
    // check if the number is a multiple of 3 and 5
    if(i % 3 === 0 && i % 5 === 0) {
      console.log('fizzbuzz')
    } // check if the number is a multiple of 3
      else if(i % 3 === 0) {
      console.log('fizz')
    } // check if the number is a multiple of 5
      else if(i % 5 === 0) {
      console.log('buzz')
    } else {
      console.log(i)
    }
  }
}

The function above simply makes the required tests using conditional statements and logs out the expected output. What you need to pay attention to in this challenge is the order of the if … else statements. Start with the double condition first (&&) and end with the case where no multiples are found. This way, you’ll be able to cover all bases.

上面的函数只是使用条件语句进行所需的测试,并注销预期的输出。 在此挑战中,您需要注意的是if … else语句的顺序。 首先从双&&条件( && )开始,直到找不到倍数的情况结束。 这样,您将能够覆盖所有基础。

#3字谜 (#3 Anagram)

A word is an anagram of another word if both use the same letters in the same quantity, but arranged differently.

如果两个单词使用的字母数量相同,但排列方式不同,则表示另一个单词的字谜。

了解挑战 (Understanding the challenge)

You can state this challenge in the following terms: write a function that checks if two provided strings are anagrams of each other; letter casing shouldn’t matter. Also, consider only characters, not spaces or punctuation. For example:

您可以用以下术语陈述这一挑战:编写一个函数,以检查两个提供的字符串是否彼此相似。 字母大小写无关紧要。 另外,仅考虑字符,而不考虑空格或标点符号。 例如:

anagram('finder', 'Friend')  --> true
anagram('hello', 'bye') --> false
关于挑战的推理 (Reasoning about the challenge)

The first thing to notice is that you’ll need to compare each letter in the two input strings, not only in terms of which letters they are but also how many of each letter there are in both strings. A way of mapping this information would look something like this:

首先要注意的是,您不仅需要比较两个输入字符串中的每个字母,还需要比较两个字符串中每个字母的数量。 映射此信息的方法如下所示:

finder --> f: 1        friend --> f: 1
           i: 1                   r: 1
           n: 1                   i: 1
           d: 1                   e: 1
           e: 1                   n: 1
           r: 1                   d: 1

A suitable data structure to hold the anagram data would be a JavaScript object literal: the key is the letter character and the value is the number of times that letter is contained in the given string.

一个适合存放字谜数据的数据结构应该是JavaScript对象文字:键是字母字符,值是字母在给定字符串中包含的次数。

Next, pay attention to these edge cases:

接下来,请注意以下情况:

  • make sure letter casing isn’t factored into the comparison; just transform both strings into either lower case or upper case

    确保在比较中不考虑字母大小写; 只需将两个字符串都转换为小写或大写
  • leave everything that isn’t a character out of the comparison; a good option would be to use a regular expression.

    将所有不是角色的东西都排除在比较之外; 一个好选择是使用正则表达式

(Solution)

Here’s how you could approach the Anagram challenge:

这是解决字谜挑战的方法:

// helper function that builds the
// object to store the data
const buildCharObject = str => {
  const charObj = {}
  for(let char of str.replace(/[^\w]/g).toLowerCase()) {
    // if the object has already a key value pair
    // equal to the value being looped over,
    // increase the value by 1, otherwise add
    // the letter being looped over as key and 1 as its value
    charObj[char] = charObj[char] + 1 || 1
  }
  return charObj
}

// main function
const anagram = (strA, strB) => {
  // build the object that holds strA data
  const aCharObject = buildCharObject(strA)
  // build the object that holds strB data
  const bCharObject = buildCharObject(strB)

  // compare number of keys in the two objects
  // (anagrams must have the same number of letters)
  if(Object.keys(aCharObject).length !== Object.keys(bCharObject).length) {
    return false
  }
  // if both objects have the same number of keys
  // we can be sure that at least both strings
  // have the same number of characters
  // Now we can compare the two objects to see if both
  // have the same letters in the same amount
  for(let char in aCharObject) {
    if(aCharObject[char] !== bCharObject[char]) {
      return false
    }
  }
  // if both the above checks succeed,
  // you have an anagram: return true
  return true
}

Notice the use of Object.keys() in the snippet above. This method returns an array containing a given object’s property names or keys in the same order as they appear in the object. In this case, the array would look like this:

请注意上面片段中Object.keys()的使用。 此方法返回一个数组,该数组包含给定对象的属性名称或键,其顺序与出现在对象中的顺序相同。 在这种情况下,数组如下所示:

['f', 'i', 'n', 'd', 'r']

This is a handy way of getting an object’s properties without performing a cumbersome loop. In this challenge, you can use it together with the .length property to check if both strings have the same number of characters, which is an important feature of anagrams.

这是一种无需执行繁琐的循环即可获取对象属性的便捷方法。 在此挑战中,您可以将其与.length属性一起使用,以检查两个字符串是否具有相同数量的字符,这是字谜的重要特征。

#4找到元音 (#4 Find the Vowels)

This is probably one of the less challenging challenges (no pun intended) — in terms of difficulty — but that doesn’t detract from the fact that you could come across it during a job interview. It goes like this.

就难度而言,这可能是挑战性较小(无双关)的挑战之一,但这丝毫不减损您在求职面试中可能遇到的挑战。 就像这样

了解挑战 (Understanding the challenge)

You can state the vowels challenge as follows: write a function that takes a string as argument and returns the number of vowels contained in that string.

您可以如下说明元音挑战:编写一个将字符串作为参数并返回该字符串中包含的元音数量的函数。

The vowels are “a”, “e”, “i”, “o”, “u”.

元音是“ a”,“ e”,“ i”,“ o”,“ u”。

Examples:

例子:

findVowels('hello') // --> 2
findVowels('why') // --> 0
(Solution)

Here’s a simple iterative solution to the Vowels challenge:

这是针对元音挑战的简单迭代解决方案:

const findVowels = str => {
  let count = 0
  const vowels = ['a', 'e', 'i', 'o', 'u']
  for(let char of str.toLowerCase()) {
    if(vowels.includes(char)) {
      count++
    }
  }
  return count
}

The one thing to notice here is the use of the .includes() method. This method is available both on strings and arrays. You can leverage it to determine if an array contains a certain value. It returns true if the array contains the specified value and false if it doesn’t.

这里要注意的一件事是使用.includes()方法。 此方法在字符串和数组上均可用。 您可以利用它来确定数组是否包含某个值。 如果数组包含指定值,则返回true;否则返回false。

There’s also a more succinct solution to this challenge, which you can set up as follows:

对于此挑战,还有一个更简洁的解决方案,您可以按以下步骤进行设置:

const findVowels = str => {
  const matched = str.match(/[aeiou]/gi)
  return matched ? matches.length : 0
}

The solution above revolves around the String’s .match() method. Its use in conjunction with a regular expression enables you to perform powerful searches. If the pattern of the regular expression you pass as argument to this method is found inside the specified string, the return value will be an array of the matched characters. In case no matches are found, .match() will return null.

上面的解决方案围绕String的.match()方法。 将其与正则表达式结合使用,可以执行功能强大的搜索。 如果在指定的字符串中找到您作为此方法的参数传递的正则表达式的模式,则返回值将为匹配字符的数组。 如果没有找到匹配项, .match()将返回null

#5斐波那契 (#5 Fibonacci)

This article couldn’t be complete without a discussion of the Fibonacci challenge, a classic question you’ll surely come across during a job interview or coding practice.

如果不讨论斐波那契挑战,这篇文章是不完整的,这是您在求职面试或编码实践中必定会遇到的经典问题。

A Fibonacci sequence is an ordering of numbers where each number is the sum of the preceding two. For example, the first ten numbers of the Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

斐波那契数列是数字的顺序,其中每个数字都是前两个数字的和。 例如,斐波那契数列的前十个数字是:0、1、1、2、3、5、8、13、21、34。

了解挑战 (Understanding the challenge)

The Fibonacci challenge goes something like this: write a function that returns the nth entry in the Fibonacci sequence, where n is a number you pass in as argument to the function.

Fibonacci的挑战是这样的:编写一个函数以返回Fibonacci序列中的 n 条目,其中n是作为参数传递给该函数的数字。

Example:

例:

fibonacci(3)  // --> 2
关于挑战的推理 (Reasoning about the challenge)

The Fibonacci challenge involves iterating over the number of times indicated by the function’s argument and returning the entry in the Fibonacci series that you find in that position.

Fibonacci挑战涉及迭代函数的参数所指示的次数,并返回在该位置找到的Fibonacci系列中的条目。

This way of stating the challenge immediately points to an iterative approach to solve the problem. Alternatively, you could try out a recursive solution, which would certainly impress the interviewer.

这种陈述挑战的方式立即指向解决问题的迭代方法。 或者,您可以尝试递归解决方案,这肯定会给面试官留下深刻的印象。

(Solution)

Here’s what the iterative solution might look like:

迭代解决方案如下所示:

const fibonacci = num => {
  // store the Fibonacci sequence you're going
  // to generate inside an array and
  // initialize the array with the first two
  // numbers of the sequence
  const result = [0, 1]

  for(let i = 2; i <= num; i++) {
    // push the sum of the two numbers
    // preceding the position of i in the result array
    // at the end of the result array
    const prevNum1 = result[i - 1]
    const prevNum2 = result[i - 2]
    result.push(prevNum1 + prevNum2)
  }
  // return the last value in the result array
  return result[num]
}

The reason why the result array above already contains the first two numbers in the series is because each entry in the Fibonacci series is made of the sum of the two preceding numbers. At the very beginning of the series there are no two numbers that you can add to produce the next number, so your loop could not possibly generate them automatically. However, you know the first two numbers are always 0 and 1, so you manually initialize your result array with those two numbers.

上面的结果数组已经包含序列中的前两个数字的原因是,斐波那契数列中的每个条目都是由前面两个数字之和组成的。 在本系列的开始,没有两个数字可以添加以产生下一个数字,因此循环可能无法自动生成它们。 但是,您知道前两个数字始终为0和1,因此您要使用这两个数字手动初始化结果数组。

Let’s move on to the recursive approach:

让我们继续进行递归方法:

const fibonacci = num => {
  // if num is either 0 or 1 return num
  if(num < 2) {
    return num
  }
  // recursion here
  return fibonacci(num - 1) + fibonacci(num - 2)
}

You keep calling fibonacci() adding up smaller and smaller numbers as arguments until you hit the base case at the top where the argument passed in is either 0 or 1.

您不断调用fibonacci()将越来越小的数字加起来作为参数,直到您到达传入的参数为0或1的顶部的基本情况为止。

结论 (Conclusion)

If you’ve just gone through a few rounds of job interviews for a front-end or JavaScript developer role, especially at the junior level, you’re likely to have come across at least one or two of the questions I listed above. Even if you haven’t, you can use all of them to practice your JS coding skills.

如果您刚刚针对前端或JavaScript开发人员角色进行了几轮工作面试,尤其是在初级级别,您可能至少遇到了我上面列出的一个或两个问题。 即使您还没有,也可以使用它们全部来练习JS编码技能。

Can you come up with alternative ways of solving the challenges? Let’s hear them!

您能否提出解决挑战的替代方法? 让我们听听他们!

翻译自: https://www.sitepoint.com/5-common-coding-interview-challenges/

javascript面试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值