JavaScript
1.内置类型
JS内置类型有7种:(6种基本数据类型)null , undefined , boolean , number , string , symbol , 和对象Object.
null 和 undefined
undefinedl : 这个变量不含有值;
null: 可以通过将变量的值设置为 null 来清空变量;
tips:undefined派生于null,因此在使用 == 进行比较时会返回true
boolean
在条件判断时,除了 undefined null false NaN '' 0 -0
其他所有值都转为 true,包括所有对象
对象Object
object是引用类型,使用过程中会遇到浅拷贝和深拷贝
浅拷贝
object.assign(target,sources)
方法
object.assign()
方法会调用target的setting()
方法和sources的getting()
方法
var A = {a:1,b:2,c:3};
var B = Object.assign({},A);
console.log('A为:'+JSON.stringify(A)); //A为:{"a":1,"b":2,"c":3}
console.log('B为:'+JSON.stringify(B)); //B为:{"a":1,"b":2,"c":3}
//修改A的值
A.a = 11;
console.log('A为:'+JSON.stringify(A)+'(修改A后)'); //A为:{"a":11,"b":2,"c":3}(修改A后)
console.log('B为:'+JSON.stringify(B)+'(修改A后)'); //B为:{"a":1,"b":2,"c":3}(修改A后)
//修改B的值
B.b = 11;
console.log('A为:'+JSON.stringify(A)+'(修改B后)'); //demo1.js:14 A为:{"a":11,"b":2,"c":3}(修改B后)
console.log('B为:'+JSON.stringify(B)+'(修改B后)'); //demo1.js:15 B为:{"a":1,"b":11,"c":3}(修改B后)
- 展开运算符(与
apply()
方法类似 apply()方法与call()方法)
function sum(x,y,z){
return x+y+z;
}
var A = [1,2,3];
console.log(sum(...A)); //6
console.log(sum.apply(null,A)) //6
浅拷贝只解决了第一层的问题,如果接下去的值中还有对象的话,那么就又回到刚开始的话题了,两者享有相同的引用。要解决这个问题,我们需要引入深拷贝。
let a = {
age: 1,
jobs: {
first: 'actress'
}
}
let b = {...a}
a.jobs.first = 'doctor'
console.log(b.jobs.first) // doctor
深拷贝
-这个问题通常用 JSON.parse(JSON.stringify(object))
来解决,其性能也是最好的
let a = {
age: 1,
jobs: {
first: 'actress'
}
}
let b = JSON.parse(JSON.stringify(a))
a.jobs.first = 'doctor'
console.log(b.jobs.first) // actress
但是这种方法有缺点:
1.会忽略undefined、symbol
2.不能序列化函数
3.不能解决循环引用的对象
let a = {
age: undefined,
sex: Symbol('famale'),
jobs: function() {},
name: 'hsn'
}
let b = JSON.parse(JSON.stringify(a))
console.log(b) // {name: "hsn"}
如果你所需拷贝的对象含有内置类型并且不包含函数,可以使用 MessageChannel()
apply()方法与call()方法
(浅谈,日后补充)
apply()
与 call()
非常相似,不同之处在于提供参数的方式。apply 使用参数数组而不是一组参数列表。apply 可以使用数组字面量,如 fun.apply(this, ['eat', 'bananas'])
,或数组对象, 如 fun.apply(this, new Array('eat', 'bananas'))
。
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
console.log(person.fullName.call(person1, "Oslo", "Norway")); //John Doe,Oslo,Norway
console.log(person.fullName.apply(person1,["Oslo", "Norway"])) //John Doe,Oslo,Norway