从JavaScript中的字符串输入检查数据类型



我正在尝试从字符串输入值中获取DataType(?(。

const data = ['1', 'hello', '[]', '{key: [value]}', '`2020-10-08`'];
function funct(data: string): DataType {
if(??) {
return Object
} else if(??) {
return Number
} else if(??) {
return Array
} else if (??) {
return Date
}
return String
}
data.map((d) => console.log(funct(data)));
// Number, String, Array, Object, Data

function funct(d) {
if(d.startsWith('{') && d.endsWith('}')) {
return typeof {}
} else if(d.indexOf('-') !== -1 && !isNaN(Date.parse(d))) {
return 'Date';
} else if(!isNaN(parseFloat(d))) {
return typeof 1
} else if(d.startsWith('[') && d.endsWith(']')) {
return typeof []
} else return typeof 'string'
}
console.log('number', funct('1'));
console.log('number', funct('123'));
console.log('string', funct('`as2d`'));
console.log('string', funct('2s2d'));
console.log('Object', funct('{}'));
console.log('Array', funct('[]')); //object :( 
console.log('Array', funct('["d", "f"]')); //object :(

您可以尝试以下操作:

function funct(d) {

if(d.startsWith('{') && d.endsWith('}')) {
return Object
} else if(d.indexOf('-') !== -1 && !isNaN(Date.parse(d))) {
return Date;
} else if(!isNaN(parseFloat(d))) {
return Number
} else if(d.startsWith('[') && d.endsWith(']')) {
return Array
} else return String
}

注意:这是在JS中测试的,所以我删除了类型注释。如果你想用TypeScript编译,请他们。

相关内容

最新更新