面试题【Day17】

2021-10-19  本文已影响0人  小王子__
本篇绪论

1, 数组去重

2,深、浅拷贝

1,数组去重

方法一:

function arrRepeat(arr) {
  var result = []
  for (var i = 0; i < arr.length; i++) {
    if (result.indexOf(arr[i]) === -1) {
      result.push(arr[i])
    }
  }
  return result
}
var arr = [1,2,2,3,3,3,5,5,5,5,5,4,4,4,4]
console.log(arrRepeat(arr))  // [1,2,3,5,4]

方法二:

function arrRepeat(arr) {
var result = [arr[0]]
arr.sort(function (a, b) {return a - b})
for (var i = 0; i < arr.length;i++) {
  if (arr[i] !== result[result.length-1]) {
    result.push(arr[i])
  }
}
return result
}
var arr = [1,2,2,3,3,3,5,5,5,5,5,4,4,4,4]
console.log(arrRepeat(arr))
2, 深、浅拷贝
浅拷贝

方法一:

var origin = {
  a: 10,
  b: [10,20,30],
  c: {
    d: 'name'
  }
}
// 浅拷贝
function shallowClone(origin) {
  var result = {}
  for (var key in origin) {
    if(origin.hasOwnProperty(key)) {
      result[key] = origin[key]
    }
  }
  return result
}
let obj = shallowClone(origin)
obj.b[2] = 300
console.log(obj)
console.log(origin)

方法二:

var origin = {
  a: 10,
  b: [10,20,30],
  c: {
    d: 'name'
  }
}
var obj = Object.assign({}, origin)
obj.b[2] = 300
console.log(obj)
console.log(origin)
// Object对象新增了一个assign()函数,用于将原对象的可枚举属性赋值到目标对象中。
浅拷贝
深拷贝

方法一:JSON的序列化和反序列化

这种会存在几个问题

function Person(name) {
  this.name = name
}
var p1 = new Person('xiaozhang')
var origin = {
  a: 10,
  b: [10,20,30],
  c: {
    d: 'name'
  },
  getName: function () {
    return 'xiaowang'
  },
  e: new RegExp('/w'),
  f: p1
}
var temp = JSON.stringify(origin)
var obj = JSON.parse(temp)
obj.b[2] = 300
console.log(obj)
console.log(origin)
JSON序列化反序列化实现深拷贝

方法二:

var origin = {
  a: 10,
  b: [10,20,30],
  c: {
    d: 'name'
  },
  getName: function () {
    return 'xiaowang'
  }
}
function deepCopy(obj) {
  var newObj = {}
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      newObj[key] = []
      for (let i in obj[key]) {
        newObj[key][i] = obj[key][i]
      }
    } else {
      newObj[key] = obj[key]
    }
  }
  return newObj
}
let obj = deepCopy(origin)
obj.b[2] = 300
console.log(obj)
console.log(origin)
image

方法三:

var origin = {
  a: 10,
  b: [10,20,30],
  c: {
    name: 'xiaowang',
    age: 18,
    friends: {
      name: 'xiaoliu',
      age: 16
    }
  }
}
function deepCopy(obj) {
  let newObj = {}
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      newObj[key] = deepCopy(obj[key])
    } else {
      newObj[key] = obj[key]
    }
  }
  return newObj
}
let obj = deepCopy(origin)
obj.c.friends.name = 'xiaolv'
console.log(obj)
console.log(origin)
image
上一篇 下一篇

猜你喜欢

热点阅读