在兩個元素 JavaScript 中查詢匹配項


我們需要編寫一個函式,如果陣列第一個元素中的字串包含陣列第二個元素字串的所有字母,則返回 true。

例如,

["hello", "Hello"], should return true because all of the letters in the second string are present
in the first, ignoring their case.

引數 ["hello", "hey"] 應返回 false,因為字串 "hello" 不包含 "y"。

最後,["Alien", "line"],應返回 true,因為 "line" 中的所有字母都出現在 "Alien" 中。

這是一個相當簡單的問題;我們只需分割陣列的第二個元素,並遍歷由此產生的陣列,以檢查第一個元素是否包含所有字元。

示例

const arrayContains = ([fist, second]) => {
   return second
   .toLowerCase()
   .split("")
   .every(char => {
      return fist.toLowerCase().includes(char);
   });
};
console.log(arrayContains(['hello', 'HELLO']));
console.log(arrayContains(['hello', 'hey']));
console.log(arrayContains(['Alien', 'line']));

輸出

控制檯中的輸出將是 −

true
false
true

更新於: 2020-08-26

172 次檢視

開啟你的 職業

完成該課程後透過認證

開始
廣告
© . All rights reserved.