检查所有数组项是否具有相同的构造函数[lodash]

时间:2019-01-23 09:20:31

标签: javascript lodash

假设我们有一堂课:

class MyClass {
    constructor() {
        this.prop1 = 1;
        this.prop2 = 2;
        this.whatever = 3;
    }
}

和两个收藏夹:

arr1 = [new MyClass(), new MyClass(), new MyClass()];
arr2 = [new MyClass(), new MyClass(), "notMyClassObject"];

问题是:
lodash是否具有方法来检测集合中的所有项目是否都具有相同的构造函数?


预期结果:

_.isArrayOf(arr1, MyClass) // => true
_.isArrayOf(arr2, MyClass) // => false

编辑

问题扩展(案例2):
假设我们有一个继承的类:

class MyChildClass extends MyClass {
    constructor() {
        this.childProp1 = 4
    }
}

和收藏集:

arr1 = [new MyClass(), new MyChildClass(), new MyClass()];
arr2 = [new MyClass(), new MyChildClass(), "notMyClassObject"]

预期结果:

_.isArrayOf(arr1, MyClass) // => true
_.isArrayOf(arr2, MyClass) // => false

2 个答案:

答案 0 :(得分:5)

这与普通JS的Array.prototype.every无关紧要,不需要库:

class MyClass {
    constructor() {
        this.prop1 = 1;
        this.prop2 = 2;
        this.whatever = 3;
    }
}

const arr1 = [new MyClass(), new MyClass(), new MyClass()];
const arr2 = [new MyClass(), new MyClass(), "notMyClassObject"];

console.log(arr1.every(i => i.constructor === MyClass));
console.log(arr2.every(i => i.constructor === MyClass));

如果需要,可以随意使用lodash:

class MyClass {
    constructor() {
        this.prop1 = 1;
        this.prop2 = 2;
        this.whatever = 3;
    }
}

const arr1 = [new MyClass(), new MyClass(), new MyClass()];
const arr2 = [new MyClass(), new MyClass(), "notMyClassObject"];

console.log(_.every(arr1, i => i.constructor === MyClass));
console.log(_.every(arr2, i => i.constructor === MyClass));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>

.constructor检查将检查是否使用new MyClass()创建了要迭代的项目-要也包含子类,请使用instanceof

class MyClass {
    constructor() {
        this.prop1 = 1;
        this.prop2 = 2;
        this.whatever = 3;
    }
}
class Child extends MyClass {
}

const arr1 = [new MyClass(), new Child(), new MyClass()];
const arr2 = [new MyClass(), new MyClass(), "notMyClassObject"];

console.log(arr1.every(i => i instanceof MyClass));
console.log(arr2.every(i => i instanceof MyClass));

答案 1 :(得分:2)

Lodash没有这种方法,但是您总是可以这样使用every

_.every([new MyClass(), new MyClass(), new MyClass()], i => i.constructor === MyClass);