Missing letters

Find the missing letter in the passed letter range and return it.

If all letters are present in the range, return undefined.

fearNotLetter("abce") should return the string d.

Passed

fearNotLetter("abcdefghjklmno") should return the string i.

Passed

fearNotLetter("stvwx") should return the string u.

Passed

fearNotLetter("bcdf") should return the string e.

Passed

fearNotLetter("abcdefghijklmnopqrstuvwxyz") should return undefined.

如何判断缺少哪个字母?

‘a’.charCodeAt()

The charCodeAt() method returns the numeric Unicode value of the character at the given index (except for unicode codepoints > 0x10000).

Syntax

  1. str.charCodeAt(index)

Parameters

index

An integer greater than or equal to 0 and less than the length of the string; if it is not a number, it defaults to 0.

MDN link 632 | MSDN link 128

Description

Note that charCodeAt() will always return a value that is less than 65536. This is because the higher code points are represented by a pair of (lower valued) “surrogate” pseudo-characters which are used to comprise the real character. Because of this, in order to examine or reproduce the full character for individual characters of value 65536 and above, for such characters, it is necessary to retrieve not only charCodeAt(i) , but also charCodeAt(i+1) (as if examining/reproducing a string with two letters). See example 2 and 3 below.

charCodeAt() returns NaN if the given index is less than 0 or is equal to or greater than the length of the string.

https://forum.freecodecamp.org/t/javascript-string-prototype-charcodeat-char-code-at-explained-with-examples/15933

  1. function fearNotLetter(str) {
  2. let startChar = str[0].charCodeAt()
  3. let endChar = str[str.length - 1].charCodeAt()
  4. let res = {}
  5. for (let char of str) {
  6. res[char.charCodeAt()] = true
  7. }
  8. while (startChar++ < endChar) {
  9. if (
  10. !res[startChar]
  11. ) {
  12. return String.fromCharCode(startChar)
  13. }
  14. }
  15. return undefined;
  16. }
  17. console.log(
  18. fearNotLetter("abce")
  19. )

使用reduce判断两者之差大于1就取上一个

  1. function fearNotLetter(str) {
  2. let res = undefined
  3. str.split('').map(x => x.charCodeAt()).reduce((prev, cur) => {
  4. if (cur - prev > 1) {
  5. res = String.fromCharCode(cur-1)
  6. }
  7. return cur
  8. })
  9. return res;
  10. }
  11. console.log(
  12. fearNotLetter("abce")
  13. )