The 20th question on BFE.dev, link is here Detect data type.
To detect data type, we should mainly use Object.prototype.toString.call() this api. This api will return a stuff like [Object xxx](here is something that represents the type of value), then we can get the string stuff through some ways.
We can use regular expression, or we can also use simple string concatenation to settle the problem.
function detectType(data) {
if(data instanceof FileReader) return 'object';
return Object.prototype.toString.call(data).slice(1, -1).split(' ')[1].toLowerCase();
}
We can use slice and two parameters of it are 1 and -1 respectively, in this way we can extract the content in square brackets. Then we can use split(’ ')(we put a blank space here) so we can get an array within two elements, and the second one is what we want.
But for this question, there is a special situation, when we encounter a FileReader, the type of it should be object but not filereader, so we should handle this scenario, so we give a if condition, check if the object is the instance of FileReader, if so, simply return ‘object’.
本文介绍了如何使用`Object.prototype.toString.call()`方法在BFE.dev中检测数据类型,包括处理FileReader特殊情况,并提到可以使用正则表达式或字符串连接来解析返回的结果。
1916

被折叠的 条评论
为什么被折叠?



