js的值引用和地址引用
发布网友
发布时间:2023-02-26 02:06
我来回答
共1个回答
热心网友
时间:2023-09-26 09:37
number 类型
var a = 1;
var b = a;
b++;
console.log(a); //1
console.log(b); //2
字符串类型
var q = 'copy';
var s = q;
s += '1';
console.log(q); //copy
console.log(s); //copy1
布尔类型
var e = false;
var w = e;
w = true;
console.log(e) //false
console.log(w) //true
数组
splice 截取 会改变原数组
//地址的引用 浅拷贝
var array = [1,2,3,4,5];
var newArray = array;
var thArray = newArray.splice(1,3);
console.log(thArray); //[2,3,4]
console.log(newArray); //[1,5]
console.log(array); //[1,5]
//循环到原始类型进行深拷贝
var arr = ['a','b','c','d','e'];
var newArr = [];
for(var i=0;i<arr.length;i++){
newArr.push(arr[i]);
}
var thArr = newArr.splice(1,3);
console.log(thArr); //["b", "c", "d"]
console.log(newArr); //["a", "e"]
console.log(arr); //["a", "b", "c", "d", "e"]
对象
//地址的引用 浅拷贝
var obj = {name:'abc',id:'1'};
var newObj = obj;
newObj.name='abcde';
console.log(obj); //{name:'abcde',id:'1'}
console.log(obj); //{name:'abcde',id:'1'}
//循环到原始类型进行深拷贝
var object = {name:'321',id:'1'};
var newObject= {};
for (var j in object){
newObject[j]=object[j]
}
newObject.name='abcde';
console.log(newObject); //{name:'abcde',id:'1'}
console.log(object); //{name:'321',id:'1'}
数字 字符串 布尔类型 为原始类型,是值引用
数组 对象类型 为地址引用
值引用为深拷贝
地址引用循环到原始类型可进行深拷贝
var nameArray = ['张三','李四'];
var descArray = ['张三是男生','李四也是男生'];
var allArray = [];
var tableObj={};
for(let i=0; i<nameArray.length;i++){
tableObj.name=nameArray[i];
tableObj.desc=descArray[i];
allArray.push(tableObj)
}
console.log(allArray) //{name: "李四", desc: "李四也是男生"}
//{name: "李四", desc: "李四也是男生"}
var nameArray = ['张三','李四'];
var descArray = ['张三是男生','李四也是男生'];
var allArray = [];
for(let i=0; i<nameArray.length;i++){
var tableObj={};
tableObj.name=nameArray[i];
tableObj.desc=descArray[i];
allArray.push(tableObj)
}
console.log(allArray) //{name: "张三", desc: "张三是男生"}
//{name: "李四", desc: "李四也是男生"}