数据类型判断
typeof 可以正确识别:Undefined、Boolean、Number、String、Symbol、Function 等类型的数据,但是对于其他的都会认为是 object,比如 Null、Date 等,所以通过 typeof 来判断数据类型会不准确。
function typeOf(obj) {
return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase();
}
console.log(typeOf([])); // 'array'
console.log(typeOf({})); // 'object'
console.log(typeOf(new Date())); // 'date'
数组去重
var unique = (arr) =>
arr.filter((item, index, array) => array.indexOf(item) === index);
//es6
var unique = arr => [...new Set(arr)]
数组扁平化
[1, [2, [3]]].flat(2) // [1, 2, 3]
//递归
function flatten(arr) {
var result = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]))
} else {
result.push(arr[i])
}
}
return result;
}
//es6
function flatten(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
深浅拷贝
//浅拷贝:只考虑对象类型。
function shallowCopy(obj) {
if (typeof obj !== "object") return;
let newObj = obj instanceof Array ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
}
return newObj;
}
//简单版深拷贝:只考虑普通对象属性,不考虑内置对象和函数。
function deepClone(obj) {
if (typeof obj !== "object") return;
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] =
typeof obj[key] === "object" ? deepClone(obj[key]) : obj[key];
}
}
return newObj;
}
实现 instanceof
function instanceOf(left, right) {
let proto = left.__proto__;
console.log()
while (true) {
if (proto === null) return false;
if (proto === right.prototype) {
return true;
}
proto = proto.__proto__;
}
}