有很多方法可以判斷數(shù)據(jù)是否是數(shù)組或字符串,以下列舉一些常見的方法:
1.通過typeof操作符判斷數(shù)據(jù)類型,如果為“string”,則數(shù)據(jù)為字符串;如果為“object”,則需要進(jìn)一步判斷是否為數(shù)組。
function isStringOrArray(data) {
if (typeof data === "string") {
console.log("數(shù)據(jù)為字符串");
} else if (typeof data === "object") {
if (Array.isArray(data)) {
console.log("數(shù)據(jù)為數(shù)組");
}
}
}
2.使用instanceof操作符判斷數(shù)據(jù)類型,如果為String,則數(shù)據(jù)為字符串;如果為Array,則數(shù)據(jù)為數(shù)組。
function isStringOrArray(data) {
if (data instanceof String) {
console.log("數(shù)據(jù)為字符串");
} else if (data instanceof Array) {
console.log("數(shù)據(jù)為數(shù)組");
}
}
3.使用Array.isArray()方法判斷數(shù)據(jù)是否為數(shù)組。文章來源:http://www.zghlxwxcb.cn/news/detail-583142.html
function isStringOrArray(data) {
if (Array.isArray(data)) {
console.log("數(shù)據(jù)為數(shù)組");
} else {
console.log("數(shù)據(jù)為字符串");
}
}
4.利用正則表達(dá)式判斷數(shù)據(jù)是否為字符串。文章來源地址http://www.zghlxwxcb.cn/news/detail-583142.html
function isStringOrArray(data) {
if (/^[a-zA-Z]+$/.test(data)) {
console.log("數(shù)據(jù)為字符串");
} else {
console.log("數(shù)據(jù)為數(shù)組");
}
}
到了這里,關(guān)于js判斷數(shù)據(jù)是否是數(shù)組或字符串的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!