引用类型有哪些?非引用类型有哪些
- 引用类型值(对象、数组、函数、正则):指的是那些保存在堆内存中的对象,变量中保存的实际上只是一个指针,这个指针执行内存中的另一个位置,由该位置保存对象。
var a;
var b;
var obj;
var obj2;
a = 1;
b = 2;
var obj = {
name: 'ruoyu',
sex: 'male',
age: 30,
friend: {
name: 'hello',
age: 100
}
}
var newObj = {};
b = a;
console.log(b);
var obj2 = obj;
var obj3 = {name: 'hello'};
var obj4 = {name: 'hello'};
obj3 === obj4
function sum(){
console.log('sum...')
}
var sum2 = sum;
sum2()
//浅拷贝
function shallowCopy(oldObj) {
var newObj = {};
for(var i in oldObj) {
if(oldObj.hasOwnProperty(i)) {
newObj[i] = oldObj[i];
}
}
return newObj;
}
//深拷贝
function deepCopy(oldObj) {
var newObj = {};
for(var key in oldObj) {
if(typeof oldObj[key] === 'object') {
newObj[key] = deepCopy(oldObj[key]);
}else{
newObj[key] = oldObj[key];
}
}
return newObj;
}
如下代码输出什么?为什么
var obj1 = {a:1, b:2};
var obj2 = {a:1, b:2};
console.log(obj1 == obj2);//false obj1和obj2为两个对象,存储在位置不同,不相等
console.log(obj1 = obj2);//[object Object] {
a: 1,
b: 2
} ;
//将obj2赋值给obj1,此时obj1和obj2在同一个位置,console.log输出obj1的值,即object {a:1, b:2}
console.log(obj1 == obj2);//true,此时obj1和obj2在同一个位置,因此为true
如下代码输出什么? 为什么
var a = 1
var b = 2
var c = { name: '饥人谷', age: 2 }
var d = [a, b, c]
var aa = a
var bb = b
var cc = c
var dd = d
a = 11
b = 22
c.name = 'hello'
d[2]['age'] = 3//c和cc存储地址内容更新为{name: 'hello', age: 3}
console.log(aa) //1
console.log(bb) //2
console.log(cc)// age: 3, name: "hello"。
console.log(dd)//[1, 2, {name: 'hello', age: 3}]
如下代码输出什么? 为什么
var a = 1
var c = { name: 'jirengu', age: 2 }
function f1(n){
++n
}
function f2(obj){ // var obj = c
++obj.age // obj = { name: 'jirengu', age: 3 }
} // c = { name: 'jirengu', age: 3 }
f1(a)
f2(c)
f1(c.age)
console.log(a) //1
console.log(c)//age: 3,name: "jirengu"
过滤如下数组,只保留正数,直接在原数组上操作
var arr = [3,1,0,-1,-3,2,-5]
function filter(arr){
for (var i = 0; i < arr.length; i++) {
if (arr[i] < 1) {
arr.splice(i,1);
filter(arr)
}
}
}
filter(arr)
console.log(arr) // [3,1,2]
过滤如下数组,只保留正数,原数组不变,生成新数组
var arr = [3,1,0,-1,-3,2,-5]
function filter(arr){
var arr2 = [];
function filter(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
arr2.push(arr[i]);
}
}
}
filter(arr)
console.log(arr2) // [3,1,2]
console.log(arr) // [3,1,0,-1,-2,2,-5]
写一个深拷贝函数,用两种方式实现
var obj = {
age: 24,
friend: {
name: 'simin',
sex: 'female',
}
}
//方法1
function copy(obj) {
var obj2 = {}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'number'
|| typeof obj[key] === 'string'
|| typeof obj[key] === 'boolean'
|| obj[key] === undefined
|| obj[key] === null) {
obj2[key] = obj[key]
} else {
obj2[key] = copy(obj[key])
}
}
}
return obj2
}
var newobj1 = copy(obj)
console.log(newobj1)
//方法2
function deepcopy(obj) {
var newobj2 = JSON.parse(JSON.stringify(obj));
return newobj2;
}
obj.age = 30
console.log(deepcopy(obj))
网友评论