2017-06-16 79 views
1

關鍵是我不是JS的專家,所以如果我的代碼是一個很大的錯誤,實際上我只是通過圍繞網絡進行的研究來學習製作一個巨大的「科學怪人」的培訓。創建一個變量與兩個.map()尋找匹配或相交兩個陣列。尋找匹配或交叉

我想採取兩組或用戶輸入的值列表,並比較他們尋找與js和jquery匹配。

首先,我將兩組輸入(不同類別)的值與.map()一起取值,以得到創建數組的值。

var x = $(".row_a").map(function() { 
    return this.value; 
}).get(); 

var y = $(".row_b").map(function() { 
    return this.value; 
}).get(); 

然後我裝盤創建包含兩個arryas separatly(如果覺得我有這個問題可能),如果我「hardcode」陣列中的腳本的下一部分按預期工作一個變量,但如果我使用上面提到的前兩個變量,腳本就會崩潰。

var arrays = [ 
    [x], 
    [y] 
    ]; 

第三部分(我真不明白深的這部分代碼),我跑這兩個arrys比較第二變量,然後用追加的結果的一段腳本。

var result = arrays.shift().reduce(function(res, v) { 
if (res.indexOf(v) === -1 && arrays.every(function(a) { 
    return a.indexOf(v) !== -1; 
    })) res.push(v); 
return res; 
}, []); 

$(".match").append("<div>Numbers " + result + " match in both lists</div>"); 

有人可以幫我undersnatd什麼是錯或giveme線索或鏈接,可以幫助?

好奇:如果我在包含數組變量使用same variable twice,該腳本工作,發現四場比賽(我認爲是正確的becouse比較同一陣列)

DEMO

-

編輯:

感謝@KarlReid和@Potorr。我不知道javascript中的交叉概念,所以現在我知道了一個更好的方法來實現結果。我會更詳細地瞭解它,試着深入理解答案。

感謝@Alexandru讓我知道sintax錯誤,從今以後它將是非常基礎和有用的。

最終結果:DEMO

(我將修改後的絲毫不差,試圖改善與他人在未來同樣的問題搜索。)

+0

所以你只是想兩個數組的交集(即,出現在兩人面前的設定值)? –

+0

是的,這是我期待的結果 – Tuux

+1

如果你有谷歌的「javascript數組交集」,我喜歡[this](https://stackoverflow.com/a/43820518/7852370)之一。 –

回答

1

這個作品在,解釋-line:

$(".action").click(function() { 
    var x = $(".row_a").map(function() { 
    return this.value; 
    }).get() 

    var y = $(".row_b").map(function() { 
    return this.value; 
    }).get() 

    // this is not really needed, if you want it: 
    // x, y are already arrays, so you don't need to wrap them with [] 
    // var arrays = [ 
    // x, 
    // y 
    //]; 

    // intersection, adapted from: https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript 
    // if you use the "arrays" variable, then change x to arrays[0] and y to arrays[1] 
    //var intersection = x.filter(function(n) { 
    // return y.indexOf(n) !== -1; 
    //}); 

    // the intersection function posted by @KarlReid is actually better and faster: 
    var intersection = x.filter(Set.prototype.has, new Set(y)); 

    // create the result string 
    var result = intersection.join(',') 

    $(".match").append("<div>Numbers " + result + " match in both lists</div>"); 
}); 

編輯:改變相交函數到所述一個張貼由@KarlReid

+1

「交集」變量未被聲明,因此「結果」變量無法分配。我認爲這將是'var intersection = x.filter(Set.prototype.has,new Set(y));' – Tuux

+0

謝謝!更新 – shotor

1

雖然更好的解決方案存在,如評論Potorr的答覆中指出,與發佈的代碼唯一的問題是這樣的:

var arrays = [ 
    [x], 
    [y] 
]; 

xy已經數組,這樣你就不會需要[ ]來包裝它們。代碼工作,如果你簡單地替換上面代碼:

var arrays = [ 
    x, 
    y 
]; 

Updated demo