1.引用类型有哪些?非引用类型有哪些2.如下代码输出什么?为什么
引用类型包括对象、数组、函数、正则表达式等
非引用类型包括数值、布尔值、字符串、null和undefined
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}
console.log(obj1 == obj2); //true 上面将obj2赋值给obj1,相当于内存地址赋给了obj,所以返回true
2.
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改变
console.log(bb) //2 非引用类型,赋值后不随a改变
console.log(cc) //{name:'hello',age:3} 引用类型与c存储的内存地址相同,所以或相互影响
console.log(dd) //[1,2,Object] 引用类型,相互影响,给d[2]添加了属性,所以变为Object
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 只是将值赋给了f1里的var n,相互不再影响
console.log(c) //{name:'jirengu',age:'3'} //调用f2触发++obj.age,因为f2将obj的地址赋值给了函数内部的var obj,所以相互影响
4.过滤如下数组,只保留正数,直接在原数组上操作
var arr = [3,1,0,-1,-3,2,-5]
function filter(arr){
var i
for (i = 0; i <arr.length; i++){
if (arr[i] <= 0){
arr.splice(i, 1)
i--
}
}
}
filter(arr)
console.log(arr) // [3,1,2]
5.过滤如下数组,只保留正数,原数组不变,生成新数组
var arr = [3,1,0,-1,-3,2,-5]
function filter(arr){
var arr2 = []
var i
for (i = 0; i < arr.length; i++){
if (arr[i] > 0){
arr2.push(arr[i])
}
}
return arr2
}
var arr2 = filter(arr)
console.log(arr2) // [3,1,2]
console.log(arr) // [3,1,0,-1,-2,2,-5]
6.写一个深拷贝函数,用两种方式实现
var obj = {
name:'chris',
gender:'male',
hobby:{
hobby1:'html',
other:{
hobby2:'jQuery',
}
}
}
function copy(obj){
var newobj = {}
var i
var a = Object.keys(obj)
for (i = 0; i < a.length; i++){
if (!(obj[a[i]] instanceof Object)){
newobj[a[i]] = obj[a[i]]
} else {
newobj[a[i]] = copy(obj[a[i]])
}
}
return newobj
}
function copy2(obj){
var result = JSON.parse(JSON.stringify(obj))
return result
}
var obj2 = copy(obj)
console.log(obj2)
var obj3 = copy2(obj)
console.log(obj3)
网友评论