1.引用类型有哪些?非引用类型有哪些
- 引用类型:对象、数组、函数、正则;
- 非引用类型:数值、字符串、布尔、null、undefined;
2.如下代码输出什么?为什么
var obj1 = {a:1, b:2};
var obj2 = {a:1, b:2};
console.log(obj1 == obj2);//false;比较引用地址,二者引用地址不同;
console.log(obj1 = obj2);// {a:1, b:2};obj2引用地址赋值给obj1执行后二者指向同一地址(obj2地址)
console.log(obj1 == obj2);//true;经过上一语句二者引用地址相同;
3.如下代码输出什么? 为什么
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;a的值赋给aa;
console.log(bb) //2;b的值赋给bb;
console.log(cc)// { name: 'hello', age: 3 };c引用地址赋给cc,c与cc引用同一个对象,不管c与cc哪个修改对象,另一个也会变;
console.log(dd)//[1, 2, Object];d的引用地址赋给dd,引用同一个数组。
4.如下代码输出什么? 为什么
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
console.log(c)// { name: 'jirengu', age: 3 }
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)
i--
}
}
}
filter(arr)
console.log(arr) // [3,1,2]
6.过滤如下数组,只保留正数,原数组不变,生成新数组
var arr = [3,1,0,-1,-3,2,-5]
function filter(arr){
var j = 0,
newarr=[]
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) // [3,1,2]
console.log(arr) // [3,1,0,-1,-2,2,-5]
7.写一个深拷贝函数,用两种方式实现
var a = {
name : 'jirengu',
age : 3,
name2 : {
number : 8,
name3 : {who : 'you'}
}
}
function copy(obj){
var newobj={}
for (var key in obj){
if ( typeof obj[key] === 'number' || typeof obj[key] === 'string' || typeof obj[key] === 'boolen' || obj[key] === null || obj[key] === undefined){
newobj[key] = obj[key]
}else {
newobj[key] = copy(obj[key])
}
}
return newobj
}
var aa = copy(a)
console.log(aa)
console.log(a)
var a = {
name : 'jirengu',
age : 3,
name2 : {
number : 8,
name3 : {who : 'you'}
}
}
function copy(obj){
var newobj = {},
str
str = JSON.stringify(obj)
newobj = JSON.parse(str)
return newobj
}
var aa = copy(a)
console.log(aa)
console.log(a)