typeof升级版,可以识别出array、object、null、nan、[]、{}
2016-12-17 10:29
337 查看
typeof 经常混淆array、object、null等,升级处理一下。
可以将这个函数放在common.js中使用。
function getTypeName(v) { var v_str = JSON.stringify(v); if (typeof v == 'object') { // 判断null if (v_str == 'null') { return 'null'; } // 判断[] if (v_str.charAt(0) == '[') { return 'array'; } // 判断{} if (v_str.charAt(0) == '{') { return 'object'; } // 判断Date对象 if (v instanceof Date) { return 'date'; } // 其他... return 'other'; } else if(typeof v == 'number') { // 判断NaN if (v_str == 'null') { return 'nan'; } return typeof v; } else { return typeof v; } } var a = 0; var b = ""; var c = null; var d = false; var e = function () {}; var f = []; var g = {}; var h; var i = new Array(); var j = new Object(); var k = new Date(); var l = NaN; console.log(getTypeName(a)); // number console.log(getTypeName(b)); // string console.log(getTypeName(c)); // null console.log(getTypeName(d)); // boolean console.log(getTypeName(e)); // function console.log(getTypeName(f)); // array console.log(getTypeName(g)); // object console.log(getTypeName(h)); // undefined console.log(getTypeName(i)); // array console.log(getTypeName(j)); // object console.log(getTypeName(k)); // date console.log(getTypeName(l)); // nan
相关文章推荐
- PHP中遍历stdclass object 报错Fatal error: Cannot use objectof type stdClass as array
- PHP“Cannot use object of type stdClass as array” (php在调用json_decode从字符串对象生成json对象时的报错)
- Cannot use object of type stdClass as array
- PHP错误Cannot use object of type stdClass as array in错误的解决办法
- [main]- ERROR 1037 Operands of Regex can be CharArray only :(Name: Regex Type: null Uid: null)
- 使用json_decode()转换返回数组或对象时出现:Cannot use object of type stdClass as array
- PHP 错误:Cannot use object of type yii\db\Command as array
- json_decode(Cannot use object of type stdClass as array)
- PHP JSON出错:Cannot use object of type stdClass as array解决方法
- Cannot use object of type stdClass as array
- PHP“Cannot use object of type stdClass as array”
- PHP报错:Cannot use object of type stdClass as array
- Cannot use object of type yii\db\Connection as array
- PHP“Cannot use object of type stdClass as array”
- Cannot use object of type PHPExcel_RichText as array
- **PHP错误Cannot use object of type stdClass as array in错误的
- 在 JavaScript 中为什么 typeof null 的结果是 object?为什么呢?
- php错误 Fatal error: Cannot use object of type stdClass as array in……
- PHP“Cannot use object of type stdClass as array”
- PHP“Cannot use object of type stdClass as array”