javascript 一共有 八种数据类型。其中包含了 基本数据类型和引用数据类型。 其中基础数据类型有: string 、 number 、 boolean 、 null、 undefined 。其中 ,引用类型有: array 、 function 、 object一共就这么8种数据类型,每一种类型都会有各自的属性或者方法,从而构建了这个丰富多彩的 javascript 世界。
const stra = 'xxx==='const numberb = 123const boolc = falseconst nulld = nullconst undedfine = undefinedconst arrayf = [1,2,3]const funcg = function() { let a = '123' console.log(a)}const objh = { a: 1, getname: function() { console.log(this.a) }}const result = function(x) { return typeof x}console.log(result(stra)) // stringconsole.log(result(numberb)) // numberconsole.log(result(boolc)) // booleanconsole.log(result(nulld)) // objectconsole.log(result(undedfine)) // undefinedconsole.log(result(arrayf)) // objectconsole.log(result(funcg)) // functionconsole.log(result(objh)) // object
区分容易混淆的数据类型
tips: 看完上面的八种 数据类型的 读取。是不是发现有三种数据还是让人有点迷糊,分别就是 null、array、object 。 这三个数据类型的 typeof 都是 object。 那如何再次区分呢?
typeof null // objecttypeof [123,133] // objecttypeof {a:1} // object// 这个时候就无法判断了, 如何操作了?const testarray = [11,22,33,44]const testnull = nullconst testobj = {a:1}const testobjectfun = function(x) { return object.prototype.tostring.call(x)}console.log( testobjectfun(testarray)) // [object array]console.log( testobjectfun(testnull)) // [object null]console.log( testobjectfun(testobj)) // [object object]
目前来看,object.prototype.tostring.call(xxx) 是一个很好判断当前对象为 什么的方法。
判断当前对象为数组的方法
const arr = [1,2,3]// es6array.isarray(arr)arr instanceof arrayarr.constructor === array// es5object.prototype.tostring.call(arr) === '[object array]'
总结:在 js 这门语言中,常见的数据类型在上文中已经作出了 展示,而且也展示了一些判断当前数据类型的方法,由于 js 是一门弱类型语言,所谓弱类型语言其实是指 数据的类型可以根据上下文的变化 发生改变。
以上就是javascript的数据类型有哪些,你能说出几个?的详细内容。
