2016-10-23 36 views
0

让我们假设我有两个不同的数组,其中一个使用大写字母(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> 
+0

这是什么** ** alfabeth? – evolutionxbox

+0

要输出它,只需执行'console.log(a)'并打开控制台。我猜,虽然'a - b'不会做你认为它做的事,看到这些是数组 – adeneo

+4

@evolutionxbox,什么是** gonne **,什么是** eksempal **,**同伴**? =>大声读出来。 – Kaiido

回答

-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' ] 
+0

谢谢!你是否愿意解释一下这里发生的事情,所以我可以学习一个littel。我非常喜欢这些循环,但是在“if”测试中会发生什么? – celllaa95

+0

'b'数组中的'if(b.indexOf(a [k])== -1)'检查'[k]'。它返回'b'中'a [k]'的索引,否则返回'-1'。在这里阅读更多关于'indexOf' [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) – Abk

+0

我想知道为什么这个答案没有用。 – Abk

-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; 
    }); 
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);