gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:18:32 26 4
gpt4 key购买 nike

假设我们有一个类:

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

最佳答案

这对于 vanilla 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));

关于javascript - 检查所有数组项是否具有相同的构造函数 [lodash],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54323808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com