1.引用类型有对象、数组、函数、正则,非引用类型有数值、布尔值、null、undefined
var obj1 = {a:1, b:2};
var obj2 = {a:1, b:2};
console.log(obj1 == obj2);//false 因为obj1,obj2是引用类型,里面只存储着地址并不相等
console.log(obj1 = obj2);//{a:1,b:2}将obj2赋值给obj1,使obj1的指针也指向obj2的地址
console.log(obj1 == obj2);//true,obj1,obj2指向同一个地址
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
console.log(aa) //1
console.log(bb) //2
console.log(cc)//{ name: 'hello, age: 3 },cc和c指向同一地址,
console.log(dd)//{2,1,name: 'hello, age: 3}同上
var a = 1
var c = { name: 'jirengu', age: 2 }
function f1(n){
++n
}
function f2(obj){
++obj.age
}
f1(a)
f2(c)
f1(c.age)
console.log(a) //1,将n赋值a,a是原始类型不会改变a的值
console.log(c)//{ name: 'jirengu', age: 3 },f2(c)使c中国的age变为3,而f1(c.age) 不会改变c中的age
5.过滤如下数组,只保留正数,直接在原数组上操作
var arr=[3,1,0,-1,-3,2,-5];
function filter(arr){
for(var i=0;i<arr.length;i++){
if(arr[i]<=0){
arr.splice(i,1);
filter(arr);
}
}
}
filter(arr);
console.log(arr); // [3,1,2]
6.过滤如下数组,只保留正数,原数组不变,生成新数组
1. var arr = [3,1,0,-1,-3,2,-5];
var arr2 = arr.filter(function(elem){
return (elem > 0);
});
alert(arr2);
alert(arr);
2. var arr = [3,1,0,-1,-3,2,-5];
var arr2 = arr.slice();
function filter(arr2) {
for(var i=0;i<arr2.length;i++) {
if(arr2[i]<=0) {
arr2.splice(i,1);
filter(arr2);
}
}
}
filter(arr2);
alert(arr);
alert(arr2);
//
var arr = [3,1,0,-1,-3,2,-5]
function filter(arr){
var newArr = [];
var j = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > 0 ) {
newArr[j] = arr[i];
j++;
}
}
return newArr;
}
var arr2 = filter(arr)
console.log(arr2)
console.log(arr)
7.写一个深拷贝函数,用两种方式实现
function deepCopy(obj){
var newobj={}
for(var key in obj){
if(typeof obj[key] == "string"|| typeof obj[key] == "number" || obj[key] == undefined ||
obj[key] == null || typeof obj[key] == "boolean"){
newobj[key] = obj[key];
}else{
newobj[key] = deepCopy(obj[key]);
}
}
return newobj;
}
var obj = {
name:"jirengu",
age:2
}
var obj2 = deepCopy(obj);
console.log(obj2);
obj.age = 26;
console.log(obj2.age);
//
function deepCopy2(obj){
return JSON.parse(JSON.stringify(obj));
}
var obj3 = {
name:"ruoyu",
age:20
}
var obj4 = deepCopy2(obj3);
console.log(obj4);
obj3.age = 27;
console.log(obj4.age);