problem:

You will create a program that will find the missing letter from a string and return it. If there is no missing letter, the program should return undefined. There is currently no test case for the string missing more than one letter, but if there was one, recursion would be used. Also, the letters are always provided in order so there is no need to sort them.

fearNotLetter("abce") should return "d".
fearNotLetter("abcdefghjklmno") should return "i".
fearNotLetter("bcd") should return undefined.
fearNotLetter("yz") should return undefined.

my solution:

  var arr = [];
  var all;
  for (var i=0; i<str.length; i++) {
    var ins = str.charCodeAt(0);
    if (str.charCodeAt(i) !== (ins + i)) {
      console.log(String.fromCharCode(ins+i));
      all = String.fromCharCode(i+ins);
      break;
    } else {
      all = undefined;
    }
  }
  return all;
}

发现和上次一样,我在进入循环什么时候return出来这里总是做错,或者想的复杂...

总结一下:return之后会直接结束function;如果for循环一变不出return直接外面来return undefined也是可以的。

basic solution:

function fearNotLetter(str) {

  for(var i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);

    if (code !== str.charCodeAt(0) + i) {
      return String.fromCharCode(code - 1);
    }  
  }
  return undefined;
}

Intermediate Code Solution:

function fearNotLetter(str) {
  var compare = str.charCodeAt(0), missing;

  str.split('').map(function(letter,index) {
    if (str.charCodeAt(index) == compare) {
      ++compare;
    } else {
      missing = String.fromCharCode(compare);
    }
  });

  return missing;
}

Advanced Code Solution:

function fearNotLetter(str) {
  var allChars = '';
  var notChars = new RegExp('[^'+str+']','g');

  for (var i = 0; allChars[allChars.length-1] !== str[str.length-1] ; i++)
    allChars += String.fromCharCode(str[0].charCodeAt(0) + i);

  return allChars.match(notChars) ? allChars.match(notChars).join('') : undefined;
}

并看不懂我不会到处乱说。好吧我努力拆解一下这个正则是什么意思...

^    匹配字符串的开始
+    重复一次或更多次 
[^x]    匹配除了x以外的任意字符 

a regular expression notChars which selects everything except str

?: Conditional(ternary)Operator

https://developer.mozilla.org...
Syntax:

condition ? expr1 : expr2

Parameters:

condition (or conditions) An expression that evaluates to true or false.
expr1, expr2 Expressions with values of any type.

原文:https://forum.freecodecamp.or...


yint
388 声望21 粉丝

转AIing