一、JS判斷字符串是否在數組中方法
在JS中,我們可以使用indexOf方法來判斷一個字符串是否在數組中。
let arr = ['apple', 'banana', 'orange'];
let str = 'banana';
if (arr.indexOf(str) !== -1) {
console.log(str + ' is in the array.');
} else {
console.log(str + ' is not in the array.')
}
當字符串存在於數組中時,indexOf方法會返回該字符串在數組中的位置。如果不存在,則返回-1。
二、VBA判斷字符串是否在數組中
在VBA中,我們可以使用InStr函數來判斷一個字符串是否在數組中。
Dim arr(2) As String
arr(0) = "apple"
arr(1) = "banana"
arr(2) = "orange"
Dim str As String
str = "banana"
If InStr(Join(arr, ","), str) > 0 Then
MsgBox str & " is in the array."
Else
MsgBox str & " is not in the array."
End If
我們需要先將數組轉換成以逗號分隔的字符串,再使用InStr函數判斷字符串是否在該字符串中出現。
三、JS判斷字符串是不是數組
在JS中,我們可以使用Array.isArray方法判斷一個變量是否是數組。
let arr = ['apple', 'banana', 'orange'];
let str = 'banana';
if (Array.isArray(arr)) {
console.log('arr is an array.');
} else {
console.log('arr is not an array.');
}
if (Array.isArray(str)) {
console.log('str is an array.');
} else {
console.log('str is not an array.');
}
Array.isArray方法會返回一個布爾值,如果變量是數組,則返回true,否則返回false。
四、判斷字符串是否在數組裡
在JS中,我們可以使用includes方法判斷一個字符串是否在數組中。
let arr = ['apple', 'banana', 'orange'];
let str = 'banana';
if (arr.includes(str)) {
console.log(str + ' is in the array.');
} else {
console.log(str + ' is not in the array.')
}
includes方法會返回一個布爾值,如果字符串存在於數組中,則返回true,否則返回false。
五、JS判斷是數組還是字符串
在JS中,我們可以使用typeof運算符判斷一個變量的類型。
let arr = ['apple', 'banana', 'orange'];
let str = 'banana';
console.log(typeof arr); // 輸出"object"
console.log(typeof str); // 輸出"string"
我們可以根據類型來判斷變量是數組還是字符串。
六、JS判斷字符串是否為數字
在JS中,我們可以使用isNaN函數判斷一個字符串是否為數字。
let str1 = '123';
let str2 = 'abc';
console.log(isNaN(str1)); // 輸出false
console.log(isNaN(str2)); // 輸出true
如果字符串可以被轉換成數字,則返回false,否則返回true。
七、JS判斷字符串都由數字組成
在JS中,我們可以使用正則表達式來判斷一個字符串是否都由數字組成。
let str1 = '123';
let str2 = 'abc';
let reg = /^\d+$/;
console.log(reg.test(str1)); // 輸出true
console.log(reg.test(str2)); // 輸出false
正則表達式/^\d+$/表示字符串由數字0-9組成,並且至少有一個字符。
八、JS判斷一個字符串是否在數組中
在JS中,除了使用indexOf方法和includes方法,我們還可以使用find方法來判斷一個字符串是否在數組中。
let arr = ['apple', 'banana', 'orange'];
let str = 'banana';
if (arr.find(item => item === str)) {
console.log(str + ' is in the array.');
} else {
console.log(str + ' is not in the array.')
}
find方法會返回數組中滿足條件的第一個元素。在這裡,我們使用箭頭函數判斷數組中是否存在和字符串相等的元素。
九、判斷字符串數組包含某字符串
在JS中,我們可以使用some方法來判斷一個字符串數組是否包含指定的字符串。
let arr = ['apple', 'banana', 'orange'];
let str1 = 'banana';
let str2 = 'pear';
if (arr.some(item => item === str1)) {
console.log('The array contains ' + str1);
} else {
console.log('The array does not contain ' + str1);
}
if (arr.some(item => item === str2)) {
console.log('The array contains ' + str2);
} else {
console.log('The array does not contain ' + str2);
}
some方法會返回數組中滿足條件的元素。在這裡,我們使用箭頭函數判斷數組中是否存在和字符串相等的元素。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/155343.html