从数组中打印字母

时间:2016-10-23 11:01:01

标签: javascript arrays

让我们假设我有两个不同的数组,其中一个包含来自(A到Z)的所有字母大写。另一个数组,我输入字母表中的字母,例如:{"K","C","L"}

我想从第一个数组中提取上面指定的字母。

例如,如果secondArr = [K,C,L]则输出为[A, B, D, E, F, G, H, I, J, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

这是我尝试过的:

<script>

    window.onload = run;

    function run() {

      a = [];
      for(i = 65; i <= 90; i++) {
        a[a.length] = String.fromCharCode(i); // A-Z
      }
      b = [];
      for(j = 70; j <= 75; j++) {
        b[b.length] = String.fromCharCode(j); // F-K
      }

      if(a !== b) {
        a - b;
      }

    }

  </script>

3 个答案:

答案 0 :(得分:1)

只需使用地图和过滤器,如:

var input = ["K", "C", "L"];
var output = Array(26).fill(0).map((x, i) => String.fromCharCode(i + 65)).filter(x => input.indexOf(x) == -1);
console.log(output);

答案 1 :(得分:-1)

a = [];
b = [];
  for(i = 65; i <= 90; i++) {
    a[a.length] = String.fromCharCode(i); // A-Z
  }
  for(j = 70; j <= 75; j++) {
    b[b.length] = String.fromCharCode(j); // F-K
  }
  a = a.filter(function(val) {
      return b.indexOf(val) == -1;
  });

答案 2 :(得分:-2)

这就是你需要的。

a = [];
b = [];
c = [];
    for(i = 65; i <= 90; i++) {
        a.push(String.fromCharCode(i)); // A-Z
      }

  for(j = 70; j <= 75; j++) {
        b.push(String.fromCharCode(j)); // F-K
      }

//option 1, you can loop through like this
      for (var k = 0; k < a.length; k++){
        if(b.indexOf(a[k]) == -1 ){
          c.push(a[k]);
        }
      }
      console.log(c);

//option 2, you can use the filter function like so
c = a.filter(function(r){
     return b.indexOf(r) == -1;
   }); 
console.log(c)



//output will be [ 'A', 'B', 'C', 'D', 'E', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]