[英]Nodejs verify array strings
我有字符串數組,我需要驗證傳入的文本 ID 是否包含在我的數組中的任何字符串中,我該如何在節點中做到這一點? (在 php 我們通常做in_array()
)但在節點中我沒有太多經驗。
sample code
var text = msg;
var myArray = [
"123",
"456"
];
if(text.id == myArray) {
// true
} else {
// false
}
PS:我知道if(text.id == myArray)
是錯誤的,我只是寫了這個,所以你可以了解我在尋找什么。
My current code
var myArray = [
"182700619",
"1566587158"
];
if (myArray.includes(msg.forward_from.id)) {
console.log("msg2:", true);
} else {
console.log("msg2:", false);
}
my incoming message structure
msg = {
message_id: 221,
from: {
id: 1566587158,
is_bot: false,
first_name: 'Test User',
username: 'testuser',
language_code: 'en'
},
chat: {
id: 1566587158,
first_name: 'Test User',
username: 'testuser',
type: 'private'
},
date: 1619746446,
forward_from: {
id: 182700619,
is_bot: false,
first_name: 'John',
last_name: 'Doe',
username: 'johndoe'
},
forward_date: 1619694506,
text: 'tesing 01!'
}
您可以使用下面的代碼來做到這一點,方法是使用 toString() 方法將 int 轉換為字符串,然后進行比較。
msg = {
message_id: 221,
from: {
id: 1566587158,
is_bot: false,
first_name: 'Test User',
username: 'testuser',
language_code: 'en'
},
chat: {
id: 1566587158,
first_name: 'Test User',
username: 'testuser',
type: 'private'
},
date: 1619746446,
forward_from: {
id: 182700619,
is_bot: false,
first_name: 'John',
last_name: 'Doe',
username: 'johndoe'
},
forward_date: 1619694506,
text: 'tesing 01!'
}
var myArray = [
"182700619",
"1566587158"
];
console.log(typeof msg.forward_from.id);
if (myArray.includes(msg.forward_from.id.toString())) {
console.log("msg2:", true);
} else {
console.log("msg2:", false);
}
上述代碼的Output如下
$node main.js
number
msg2: true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.