LeetCode刷题准备之常用JS数据结构
发布时间 :
阅读 :
1. JS基本数据类型
基本类型(值类型):Number, String, Boolean, Symbol, null, undefined。在内存中占据固定大小,保存在堆栈中
引用类型:Object, Function, Array, Date, RegExp, 特殊的基本包装类型(String, Number, Boolean)以及单位内置对象(Global, Math)等引用类型的值是对象 保存在对内存中,栈内存存储的是对象的变量标识符以及对象在堆内存中存储的地址。
2. JS中的类型检测
typeof
1 2 3 4 5 6 7 8 9 10 11
| console.log(typeof 1); console.log(typeof true); console.log(typeof 'mc'); console.log(typeof Symbol) console.log(typeof function(){}); console.log(typeof console.log()); console.log(typeof []); console.log(typeof {}); console.log(typeof null); console.log(typeof undefined);
|
Pros: 能够快速区分基本的数据类型
Cons: typeof不能将Object、Array、Null进行区分,返回为object
instanceof
1 2 3 4 5 6 7
| console.log(1 instanceof Number); console.log(true instanceof Boolean); console.log('str' instanceof String); console.log([] instanceof Array); console.log(function(){} instanceof Function); console.log({} instanceof Object);
|
Pros: 能够区分Array, Object和Function
Cons: 基本数据类型不能区分
Object.prototype.toString.call()
1 2 3 4 5 6 7 8 9 10
| var toString = Object.prototype.toString; console.log(toString.call(1)); console.log(toString.call(true)); console.log(toString.call('mc')); console.log(toString.call([])); console.log(toString.call({})); console.log(toString.call(function(){})); console.log(toString.call(undefined)); console.log(toString.call(null));
|
Pros: 类型的精确判断
Cons: 调用方式复杂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| let greet = { text: "hello", sayhi: function() {console.log(this.text)}, sayBye: function() {console.log("bye")}, set: na => { this.text = na } }
let greet1 = { text: "hello", sayhi: function() {console.log(this.text)}, sayBye: function() {console.log("bye")}, set: function(na) { this.text = na } }
|
在调用greet1/greet.set(‘world’)后
其中,展开的值是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| greet {text: "hello", sayhi: ƒ, sayBye: ƒ, set: ƒ} sayBye: ƒ () sayhi: ƒ () set: na => { this.text = na } text: "hello" __proto__: Object
greet1 {text: "world", sayhi: ƒ, sayBye: ƒ, set: ƒ} sayBye: ƒ () sayhi: ƒ () set: ƒ (na) text: "world" __proto__: Object
var anotherObject = { a: 2 }
var myObject = Object.create(anotherObject)
anotherObject.a; myObject.a;
anotherObject.hasOwnProperty("a") myObject.hasOwnProperty("a")
myObject.a++; myObject.a;
myObject.hasOwnProperty("a")
function foo() { }
var a = new foo() Object.getPrototypeOf(a) === foo.prototype
|
对于new来调用的函数,或者说发生构造函数调用时,会自动执行如下操作:
- 创建(或者说构造)一个全新的对象
- 这个新对象会被执行”Prototype”连接
- 这个对象会被绑定到函数调用的this
- 如果函数没有返回其他对象,那么new表达式中的函数调用会自动返回这个新对象
所以对于上面的一步,就是将a内部的Prototype连接到foo.prototype所指向的对象。
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 miaozixiong@gmail.com