复习JS基础之原型链和数组操作方法等

33 阅读1分钟

一. 检查是否是类的对象实例的实现

思路

随着原型链一直往上找即可

解题方法

利用Object.getPrototypeOf方法在原型链上比较即可

实现

/**
 * @param {any} object
 * @param {any} classFunction
 * @return {boolean}
 */
var checkIfInstanceOf = function(obj, classFunction) {
    // 如果是classFunction 是null、undefined等,直接返回false
    if ([null, undefined].includes(classFunction)) return false;
    // 循环查找比较obj上的原型与隐式原型是否相等,相等就说明在classFunction的原型链上,返回true
    while(obj) {
        let proto = Object.getPrototypeOf(obj);
        let prototype = classFunction.prototype;
        if (proto === prototype) return true;
        obj = proto;
    }
    return false;
};

/**
 * checkIfInstanceOf(new Date(), Date); // true
 */

二. 数组原型对象的最后一个元素

思路

获取到数组长度,返回array[array.length - 1]即可, 当然这里还有其他很多种方法,就不赘述了

解题方法

根据其长度获取最后一项, 也可以调用数组的at方法等

Array.prototype.last = function() {
    // 根据长度获取最后一项
    // return this[this.length - 1] ?? - 1;
    // 直接调用数组的at方法也可以获取都最后一项
    return this.at(-1) ?? -1;
};
/**
 * const arr = [1, 2, 3];
 * arr.last(); // 3
 */