簡體   English   中英

獲取數組中的所有元素 (Javascript)

[英]Getting All Elements In An Array (Javascript)

我正在嘗試檢查一個字符串是否包含我存儲在數組中的某些單詞......但是我是 JS 的新手,所以我不知道如何檢查數組中的所有元素。

這是一個例子:

const fruits = ["apple", "banana", "orange"]

我實際上是在檢查是否有人在聊天中發送臟話。

if(message.content.includes(fruits)){executed code}

但是我的問題是當我檢查水果時它會做任何事情但是當我檢查數組中的特定元素時fruits[0] //returns apple它實際上會檢查那個......所以我的問題/問題是我如何檢查數組中所有元素的字符串,而不僅僅是蘋果。

您對includes的用法是錯誤的。

來自 MDN:

includes() 方法確定數組是否在其條目中包含某個值,並根據需要返回 true 或 false。

arr.includes(valueToFind[, fromIndex])

 const fruits = ["apple", "banana", "orange"]; const swearWord = "orange"; // execute is available if (fruits.includes(swearWord)) console.log("Swear word exists."); else console.log("Swear word doesn't exist.");

要檢查其他方式,如果字符串包含數組的臟話:

 const fruits = ["apple", "banana", "orange"]; const swearWord = "this contains a swear word. orange is the swear word"; // execute is available if (checkForSwearWord()) console.log("Swear word exists."); else console.log("Swear word doesn't exist."); function checkForSwearWord() { for (const fruit of fruits) if (swearWord.includes(fruit)) return true; return false; }

你得到它相反的方式。 您必須在數據數組上使用 .includes 來檢查數組是否包含您要查找的單詞。

 const fruits = ["apple", "banana", "orange"] console.log(fruits.includes("banana")) console.log(fruits.includes("something not in the array"))

反轉它:

if(fruits.includes(message.content)){executed code};

Array.includes的文檔。 您正在使用String.includes方法。 或者,您也可以使用indexOf方法。

我會在這里使用交叉路口。 以防萬一你不知道那是什么......

交集是兩個 arrays 共有的元素。

例如

swearWords = ["f***", "s***"];
messageWords = ["I", "am", "angry...", "f***", "and", "s***"];
let intersection = messageWords.filter(x => swearWords.includes(x));
console.log(intersection) //-> ["f***", "s***"]

試試這個。

fruits.forEach(fruit => {
    if (message.content.includes(fruit)) {
        console.log('true')
        return;
    }
    console.log('false')
})

希望這有幫助。

你可以嘗試使用Array some方法

const fruits = ["apple", "banana", "orange"]
const containsFruit = fruit => message.content.includes(fruit);

if(fruits.some(containsFruit)) { executed code }

containsFruit 是一個 function,如果在 message.content 中找到水果,它將返回 true

如果發現數組中的任何項目包含在 message.content 中,fruits.some(containsFruit) 將為真

另一種方法是使用正則表達式。

對於大型消息字符串,這可能比在循環中調用 .includes() 與數組(每次都需要遍歷整個字符串)更快。 然而,這應該被測試。

let fruits = ["apple", "banana", "orange"]
let fruits_regex = fruits.map(f => f.replace(/(?=\W)/g, '\\')).join('|');  // escape any special chars
// fruits_regex == "apple|banana|orange"

let message = 'apple sauce with oranges';
let matches = [ ...message.matchAll(fruit_regex) ]
// [
//   ["apple",  index:  0, input: "apple sauce with oranges", groups: undefined]
//   ["orange", index: 17, input: "apple sauce with oranges", groups: undefined]
// ]

const fruits = ["apple", "banana", "orange"]
if(fruits.some(x => message.content.includes(x))){
  /* executed code */
};

暫無
暫無

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

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