检查对象是否为 Node.JS 中特定对象实例的数组

Check if object is Array of instance of specific object in Node.JS

我在 Node JS

中有一个简单的 class
class Animal {
    constructor(name) {
      this.name = name;
      // more fields ...
    }
}

let objects = [];
objects.push(new Animal('Dog'));
objects.push(new Animal('Cat'));
objects.push(new Animal('Dinosaur'));
console.log(objects);

检查此数组是否为 instanceof Animal 对象的最佳方法是什么,而无需循环检查每个元素的 instanceof

使用Array.prototype.every():

class Animal {
    constructor(name) {
      this.name = name;
      // more fields ...
    }
}

let objects = [];
objects.push(new Animal('Dog'));
objects.push(new Animal('Cat'));
objects.push(new Animal('Dinosaur'));
console.log(objects.every(x => x instanceof Animal));