JS实用方法-持续更新

5/9/2021 JavaScript效率ES6

本文用于记录工作、学习、生活中常用到的 JavaScript 方法,如有不妥之处,欢迎指出修正!

# 文章目录

# 一、JavaScript 判断数据类型

function type(o) {
  const s = Object.prototype.toString.call(o);
  return s.slice(s.indexOf(" ") + 1, s.length - 1).toLowerCase();
}
console.log(Object.prototype.toString.call(async function() {})); //[object AsyncFunction]
console.log(Object.prototype.toString.call(async () => {})); //[object AsyncFunction]
console.log(Object.prototype.toString.call("jerry")); //[object String]
console.log(Object.prototype.toString.call(12)); //[object Number]
console.log(Object.prototype.toString.call(true)); //[object Boolean]
console.log(Object.prototype.toString.call(undefined)); //[object Undefined]
console.log(Object.prototype.toString.call(null)); //[object Null]
console.log(Object.prototype.toString.call({ name: "jerry" })); //[object Object]
console.log(Object.prototype.toString.call(function() {})); //[object Function]
console.log(Object.prototype.toString.call([])); //[object Array]
console.log(Object.prototype.toString.call(new Date())); //[object Date]
console.log(Object.prototype.toString.call(/\d/)); //[object RegExp]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

看不懂?点这里:浅谈 Object.prototype.toString.call(obj)功能及原理 (opens new window)

# 二、深拷贝(循环引用未解决)

const oldObj = {
  name: "彭先生",
  age: 18,
  colors: ["red", "green", "blue", "yelloww"],
  friend: {
    name: "小彭",
  },
};
function deepClone(obj) {
  if (typeof obj != "object" || typeof obj == null) {
    return obj;
  }

  let result;

  if (obj instanceof Array) {
    result = [];
  } else {
    result = {};
  }

  // for in 循环拿到的是键(数组是下标) for of拿到的是值
  for (let key in obj) {
    // hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性
    // 不拷贝原型上的属性
    if (obj.hasOwnProperty(key)) {
      result[key] = deepClone(obj[key]);
    }
  }
  return result;
}

const newObj = deepClone(oldObj);

newObj.friend.name = "a";

console.log("oldObj: ", oldObj);
console.log("newObj: ", newObj);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

看不懂?点这里:手写深拷贝【JS 面试题】 (opens new window)

最后更新于: 2021年9月15日星期三晚上10点10分
Faster Than Light
Andreas Waldetoft / Mia Stegmar