[英]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()時,它起作用了。 有人可以解釋發生了什么嗎?
我只是用一個非常基本的測試示例測試了您的代碼,如下所示:
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.