var isEmptyArray = function (array) {
if (typeof array !== 'undefined' && array.length > 0) {
}
isEmptyArray(myArray);
如何重新编写以上内容才能使用:
myArray.isEmptyArray();
答案 0 :(得分:4)
只是javascript:
Array.prototype.isEmptyArray = function() {
return this.length === 0;
}
打字稿:
interface Array<T> {
isEmptyArray(): boolean;
}
Array.prototype.isEmptyArray = function() {
return this.length === 0;
}
上述解决方案适用于Array
的所有实例,例如:
let a = [];
console.log(a.isEmptyArray()); // true
a.push(1);
console.log(a.isEmptyArray()); // false
您可以创建自己的数组类,然后在那里实现所需的方法(不影响其他Array
实例):
class MyArray<T> extends Array<T> {
public isEmptyArray(): boolean {
return this.length === 0;
}
}
let a1 = [];
console.log(a1.isEmptyArray()); // Uncaught TypeError: a.isEmptyArray is not a function
let a2 = new MyArray<any>();
console.log(a2.isEmptyArray()); // true
当您使用其他不知道您在Array
原型中所做的更改的js库时,这种方法很有用。