示例
例一
let a = 12;
let b = a;
b = 13;
console.log( a, b );
例二
let n = [ 10, 20 ];
let m = n;
n[2] = '30';
console.log( m === n )
let n = [ 1, 2 ];
let m = n;
let x = m;
m[0] = 10;
x = [ 3, 4 ];
x[0] = 20;
m = x;
m[1] = 30;
n[2] = 40;
console.log( n, m, x );
let a = {
n: 1
}
let b = a;
a.x = a = {
n: 2
};
console.log( a, b )
/* 反复引用, 堆栈溢出 */
let a = {
x: 1
}
let b = a;
b.x = a
console.log(a);
例三
/*
* 引用数据类型造成的问题
*/
let res = {
data: {
list: [ 1, 2, 3 ]
},
code: 200,
isSuccess: true
}
function handleList( list ){ //
list.splice(4, 1, 6);
return list;
}
const list = handleList( res.data.list );
console.log( list == res.data.list );
null 和 undefined
/*
1. 检测数据是否被定义过
2. 当数据定义成 null, 被视为是引用类型,分配堆内存地址,只是堆内存地址没有指向任何属性值,所以其类型依然是 object
*/
function isNotExist( param ){
return param == null;
}
栈( stack )
- 创建一个变量,放置在当前栈内存变量存储空间
- 创建一个值, 并把这个值放置在当前栈内存值区域中
- 赋值,变量和值关联起来
堆( heap )
- 在内存中分配出一块新内存,用于存储引用类型
- 把对象中的键值依次存储到堆内存中
- 把堆内存地址和变量关联
- 如果在堆内存中值存储空间是复杂数据类型,也会创建新的堆存储空间
数据拷贝
浅拷贝
Object.assign
const json = {
name: 'baidu'
}
const assignJson = Object.assign({}, json );
const json = [ 1, 2, 3 ];
const assignJson = Object.assign([], json );
解构
const json = {
name: 'baidu'
}
const json2 = {
...json
}
console.log( json == json2 );
深拷贝
JSON.string, JSON.parse
const json = {
name: 'baidu'
}
const parseJson = JSON.parse( JSON.stringify( json ) );
const json1 = {
name: 1,
age: 3,
data: { sex: 0 }
};
const json2 = {
name: 1,
data: { sex: 0 },
age: 3
};
function jsonDiff( p1, p2, keys ){
return JSON.stringify( p1, keys ) == JSON.stringify( p2, keys )
}
console.log( jsonDiff( json1, json2) ); // false;
console.log( jsonDiff( json1, json2, [ 'name', 'age', 'data' ]) ); // true
递 归
const getType = function( param ){
const toString = Object.prototype.toString;
return toString.call( param ).replace(/^[object\s+(.+)]$/,'$1' ).toLowerCase();
}
function deepCopy( object ){
if( getType(object) === 'object'){
const newObject = {};
for( let key in object ){
newObject[key] = deepCopy( object[key] )
}
return newObject;
}else if( getType(object) == 'array' ){
const newArr = [];
for( let i = 0; i < arr.length; i ++ ){
newArr.push( deepCopy( arr[i] ) );
}
return newArr
}else{
return object
}
}
防止数据篡改
const
const a = {};
const b = 12;
Object.freeze()
无法新增、删除、改变属性值
const json = {
name: 'baidu',
age: 100
}
const freezeIson = Object.freeze(json);
console.log( json === freezeIson ); // true
Object.seal()
无法新增、删除属性值, 但可以更改其属性值
const json = {
name: 'baidu',
age: 100
}
const sealJson = Object.seal( json );
Object.defineProperty()
对具体的属性值描述,用来规定 属性的可操作性等
let json = {
data: {
name: 'baidu',
age: 100
}
}
Object.defineProperty( json, 'data', {
enumerable: false,
configurable: false,
writable: false,
});
json.data = {}; console.log( json );
Proxy()
与 Reflect 共同 规范了对象属性的操作
let json = {
name: 'company',
age: 100
}
let jsonProxy = new Proxy( json, {
set( target, propKey, receiever ){
return target
},
deletePropty( target, PropKey ){
return target
}
})