当前位置:网站首页>引用变量赋值

引用变量赋值

2022-08-11 05:17:00 -加油

1、修改数据
对象:

let obj1 = {
    
    name:'1111'
}
let obj2 = obj1
console.log(obj1);//{ name: '1111' }
console.log(obj2);//{ name: '1111' }
//修改对象内部数据 会影响
obj2.age = 18
// //或者
// obj2['age'] = 18
console.log(obj1);//{ name: '1111', age: 18 }
console.log(obj2);//{ name: '1111', age: 18 }

数组:

let arr1 = ['盛明兰','小桃']
let arr2 = arr1
console.log(arr1);//[ '盛明兰', '小桃' ]
console.log(arr2);//[ '盛明兰', '小桃' ]
arr1[2] = '丹橘'
console.log(arr1);//[ '盛明兰', '小桃', '丹橘' ]
console.log(arr2);//[ '盛明兰', '小桃', '丹橘' ]

2、指向另一个对象

let obj1 = {
    
    name:'1111'
}
let obj2 = obj1
console.log(obj1);//{ name: '1111' }
console.log(obj2);//{ name: '1111' }
//obj1 指向另一对象
obj1 = {
    
    age:18
}
console.log(obj1);//{ age: 18 }
//obj2仍然指向之前的
console.log(obj2);//{ name: '1111' }
let arr1 = ['盛明兰','小桃']
let arr2 = arr1
console.log(arr1);//[ '盛明兰', '小桃' ]
console.log(arr2);//[ '盛明兰', '小桃' ]
//arr1 指向新的
arr1 = ['顾廷烨','石头']
console.log(arr1);//[ '顾廷烨', '石头' ]
//arr2 仍然是之前的
console.log(arr2);//[ '盛明兰', '小桃' ]

3、传参
对象:

let obj1 = {
    
    name:'1111'
}
let obj2 = obj1
console.log(obj1);//{ name: '1111' }
console.log(obj2);//{ name: '1111' }
//将obj1 的地址 拷贝给obj
function fn(obj){
    
//修改对象内部数据 会影响
    obj.name = '2222'
}
//传的实参是引用类型 传的是地址
fn(obj1)
console.log(obj1);//{ name: '2222' }
console.log(obj2);//{ name: '2222' }

数组:

let arr1 = ['盛明兰','小桃']
let arr2 = arr1
console.log(arr1);//[ '盛明兰', '小桃' ]
console.log(arr2);//[ '盛明兰', '小桃' ]
function fn(arr){
    
//修改内部数据 会影响
    arr.push('丹橘')
}
fn(arr1)
console.log(arr1);//[ '盛明兰', '小桃', '丹橘' ]
console.log(arr2);//[ '盛明兰', '小桃', '丹橘' ]

指向新的对象:
对象:

let obj1 = {
    
    name:'1111'
}
let obj2 = obj1
console.log(obj1);//{ name: '1111' }
console.log(obj2);//{ name: '1111' }
//将obj1 的地址 拷贝给obj
function fn(obj){
    
    //这里的obj 指向另一对象了 与obj1无关 也不会修改到obj1
    obj = {
    
        name:'2222'
    }
}
fn(obj1)
console.log(obj1);//{ name: '1111' }
console.log(obj2);//{ name: '1111' }

数组:

let arr1 = ['盛明兰','小桃']
let arr2 = arr1
console.log(arr1);//[ '盛明兰', '小桃' ]
console.log(arr2);//[ '盛明兰', '小桃' ]
//传的实参是引用类型 传的是地址
function fn(arr){
    
    //指向新的引用类型 
    arr = ['顾廷烨','石头']
}
fn(arr1)
console.log(arr1);//[ '盛明兰', '小桃']
console.log(arr2);//[ '盛明兰', '小桃']

例子:

let x = [1,2]
//传的是地址
function fn(y){
    
    y[0] = 100  //修改内部数据 同时修改了实参的数组x
    y = [3]    // 指向新的
    y[1] = 4
    console.log(y);// [ 3, 4 ]
}
console.log(x);//[ 1, 2 ]
fn(x)
console.log(x);//[ 100, 2 ]
原网站

版权声明
本文为[-加油]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_51040174/article/details/125306579