数据类型判断

typeof 可以正确识别:Undefined、Boolean、Number、String、Symbol、Function 等类型的数据,但是对于其他的都会认为是 object,比如 Null、Date 等,所以通过 typeof 来判断数据类型会不准确。

  1. function typeOf(obj) {
  2. return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase();
  3. }
  4. console.log(typeOf([])); // 'array'
  5. console.log(typeOf({})); // 'object'
  6. console.log(typeOf(new Date())); // 'date'

数组去重

  1. var unique = (arr) =>
  2. arr.filter((item, index, array) => array.indexOf(item) === index);
  3. //es6
  4. var unique = arr => [...new Set(arr)]

数组扁平化

  1. [1, [2, [3]]].flat(2) // [1, 2, 3]
  1. //递归
  2. function flatten(arr) {
  3. var result = [];
  4. for (var i = 0, len = arr.length; i < len; i++) {
  5. if (Array.isArray(arr[i])) {
  6. result = result.concat(flatten(arr[i]))
  7. } else {
  8. result.push(arr[i])
  9. }
  10. }
  11. return result;
  12. }
  13. //es6
  14. function flatten(arr) {
  15. while (arr.some(item => Array.isArray(item))) {
  16. arr = [].concat(...arr);
  17. }
  18. return arr;
  19. }

深浅拷贝

  1. //浅拷贝:只考虑对象类型。
  2. function shallowCopy(obj) {
  3. if (typeof obj !== "object") return;
  4. let newObj = obj instanceof Array ? [] : {};
  5. for (let key in obj) {
  6. if (obj.hasOwnProperty(key)) {
  7. newObj[key] = obj[key];
  8. }
  9. }
  10. return newObj;
  11. }
  12. //简单版深拷贝:只考虑普通对象属性,不考虑内置对象和函数。
  13. function deepClone(obj) {
  14. if (typeof obj !== "object") return;
  15. var newObj = obj instanceof Array ? [] : {};
  16. for (var key in obj) {
  17. if (obj.hasOwnProperty(key)) {
  18. newObj[key] =
  19. typeof obj[key] === "object" ? deepClone(obj[key]) : obj[key];
  20. }
  21. }
  22. return newObj;
  23. }

实现 instanceof

  1. function instanceOf(left, right) {
  2. let proto = left.__proto__;
  3. console.log()
  4. while (true) {
  5. if (proto === null) return false;
  6. if (proto === right.prototype) {
  7. return true;
  8. }
  9. proto = proto.__proto__;
  10. }
  11. }