Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组去重全攻略、浅拷贝与深拷贝 #24

Open
hrpc opened this issue Apr 8, 2019 · 0 comments
Open

数组去重全攻略、浅拷贝与深拷贝 #24

hrpc opened this issue Apr 8, 2019 · 0 comments

Comments

@hrpc
Copy link
Owner

hrpc commented Apr 8, 2019

1:两层循环,兼容性最好IE6-8都可以

var arr = [1,2,3,4,5,5,4,3,2,1,11]
function unique(arr) {
  // 结果数组
  var res = []
  for (var i = 0, len = arr.length; i < len; i++) {
    for (var j = 0, resLen = res.length; j < resLen; j++) {
      if (res[j] === arr[i]) {
        break;
      }
    }
    // 如果arr[i]是唯一的,那么res的循环结束时,j 等于resLen
    if (j === resLen) {
      res.push(arr[i])
    }
  }
  return res
}
  1. 两层循环的简化版,使用indexOf
const arr = [1,2,3,4,5,5,4,3,2,1,11]
function unique(arr) {
  var res = []
  for (var i = 0, len = arr.length; i < len; i++) {
    if (res.indexOf(arr[i]) === -1) {
      res.push(arr[i])
    }
  }
  return res
}
  1. Set去重
var arr = [1,2,3,4,5,5,4,3,2,1,11]
function unique(arr) {
  return Array.from(new Set(arr))
}

4.filter去重

var arr = [1,2,3,4,5,5,4,3,2,1,11]
function unique(arr) {
 return arr.filter((item, index) => {
  return arr.indexOf(item) === index
 })
}

深拷贝
-- 目的就是要拷贝值而不是仅仅拷贝引用
1: JSON方法

const obj = {
  name: '李四',
  obj2: {
    key1: 'str'
  }
}
function copy(obj) {
  return JSON.parse(JSON.stringify(obj))
}
// 这个方法就很简单,直接将原对象序列化为JSON字符串,再用parse反序列化回来
// 问题就是对Function, 对象循环引用,symbol对象,正则不起作用

2:循环递归

const obj = {
  name: '李四',
  obj2: {
    key1: 'str'
  }
}
function copy(obj) {
  const newObj = obj.constructor === Array ? [] : {}
  if (tyoepf obj !== 'object') {
    return
  }
  Object.keys(obj).forEach(key => {
    newObj[key] = tyoepf obj[key] === 'object' ? copy(obj[key]) : obj[key]
  })
  return newObj
}
// 这个方式的问题和前面一样
@hrpc hrpc changed the title 数组去重全攻略 数组去重全攻略、浅拷贝与深拷贝 Apr 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant