簡體   English   中英

比較兩個數組並在Javascript中查找匹配項

[英]Compare two array and find match in Javascript

for(var i = 0; i < textList.length; i++){
    for(var j = 0; j < titles.length; j++){
        if(textList[i] === titles[j]){
            console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
        }
    }
}

這是我的代碼,但不會返回匹配項。 我嘗試了==和===。 但是當我測試.includes()時,它起作用了。 有人可以解釋發生了什么嗎?

如果確定所有元素的類型均為String,則可以使用.search()方法:

原型搜索

它將返回比賽的位置,如果它在任何位置都匹配,則返回-1,所以> 0表示匹配。

我只是用一個非常基本的測試示例測試了您的代碼,如下所示:

let textList = ['book1', 'book2','book3']

let titles = ['book', ' tester', 'not_this', 'book2']

for(var i=0; i<textList.length;i++){
    for(var j=0; j<titles.length;j++){
        if (textList[i] === titles[j]){
            console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
        }
    }
}

而且我得到了預期的結果it includes my book2 the match is book2 counter 1因此建議您使用此特定代碼查看輸入數組。

關於您的問題,為什么.includes()可以工作,而不能這樣做,再次,我們將需要檢查您的輸入數組,但我冒昧猜測這與該函數中的類型檢查有關。

最后,正如其他人所建議的那樣,還有其他(更簡潔)的方法可以通過內置的數組函數來實現,但是您最初的問題是,為什么該代碼尤其無法工作,所以我將其遺漏了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM