There are many ways to determine whether the data is an array or a string, some common methods are listed below:
1. Use the typeof operator to determine the data type. If it is "string", the data is a string; if it is "object", you need to further determine whether it is an array.
function isStringOrArray(data) {
if (typeof data === "string") {
console.log("数据为字符串");
} else if (typeof data === "object") {
if (Array.isArray(data)) {
console.log("数据为数组");
}
}
}
2. Use the instanceof operator to determine the data type. If it is String, the data is a string; if it is Array, the data is an array.
function isStringOrArray(data) {
if (data instanceof String) {
console.log("数据为字符串");
} else if (data instanceof Array) {
console.log("数据为数组");
}
}
3. Use the Array.isArray() method to determine whether the data is an array.
function isStringOrArray(data) {
if (Array.isArray(data)) {
console.log("数据为数组");
} else {
console.log("数据为字符串");
}
}
4. Use regular expressions to determine whether the data is a string.
function isStringOrArray(data) {
if (/^[a-zA-Z]+$/.test(data)) {
console.log("数据为字符串");
} else {
console.log("数据为数组");
}
}