文章目录
- 检查是否是类的对象实例
- 数组原型对象的最后一个元素
- 计数器
检查是否是类的对象实例
请你编写一个函数,检查给定的值是否是给定类或超类的实例。
可以传递给函数的数据类型没有限制。例如,值或类可能是 undefined 。
示例 1:
输入:func = () => checkIfInstance(new Date(), Date)
输出:true
解释:根据定义,Date 构造函数返回的对象是 Date 的一个实例。示例 2:
输入:func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstance(new Dog(), Animal); }
输出:true
解释:
class Animal {};
class Dog extends Animal {};
checkIfInstanceOf(new Dog(), Animal); // true
Dog 是 Animal 的子类。因此,Dog 对象同时是 Dog 和 Animal 的实例。示例 3:
输入:func = () => checkIfInstance(Date, Date)
输出:false
解释:日期的构造函数在逻辑上不能是其自身的实例。示例 4:
输入:func = () => checkIfInstance(5, Number)
输出:true
解释:5 是一个 Number。注意,“instanceof” 关键字将返回 false。
思想:实例对象的__proto__
指向该实例对象的原型对象的prototype
对象,所以判断给定值是否是给定类的实例对象,直接判断obj.__proto__ === classFunction.prototype
即可,由于原型链的存在,所以还需判断obj.__proto__
的__proto__
是否指向原型对象的prototype
对象
prototype对象:用于放某同一类型实例的共享属性和方法,实质上是为了内存着想
每个实例对象都有一个__proto__
属性,指向构造函数的prototype
对象
var checkIfInstanceOf = function (obj, classFunction) {if (obj === null ||obj === undefined ||classFunction === null ||classFunction === undefined)return false;return (obj.__proto__ === classFunction.prototype ||checkIfInstanceOf(obj.__proto__, classFunction));
};
数组原型对象的最后一个元素
请你编写一段代码实现一个数组方法,使任何数组都可以调用array.last()
方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1 。
你可以假设数组是 JSON.parse
的输出结果。
示例 1 :
输入:nums = [null, {}, 3]
输出:3
解释:调用 nums.last() 后返回最后一个元素: 3。
示例 2 :
输入:nums = []
输出:-1
解释:因为此数组没有元素,所以应该返回 -1。
方法一:将 Nullish 合并运算符与 Array.prototype.at()
方法结合使用
Nullish:空合并运算符(??)。如果不为 null 或 undefined,则返回左侧操作数,否则返回右侧操作数。
Array.prototype.at()
方法接受一个整数值,并返回该索引处的元素,允许使用正整数和负整数。负整数从数组末尾开始计数。
Array.prototype.last = function() {return this.at(-1) ?? -1;
}
方法二:为最后一个属性定义一个 getter来增强数组原型,getter 函数将返回另一个函数,该函数返回数组的最后一个元素,如果数组为空,则返回 -1。
Object.defineProperty(Array.prototype, 'last', {get: function() {return () => this.length ? this[this.length - 1] : -1;}
});
当你定义一个 getter 时,你实际上是把 last 当作一个属性而不是一个函数。因此,它是通过
array.last
而不是array.last()
访问的。如果您将数组的最后一个元素视为该数组的属性,而不是函数的结果