【问题标题】:Check if object is Array of instance of specific object in Node.JS检查对象是否是 Node.JS 中特定对象实例的数组
【发布时间】:2021-08-26 16:51:50
【问题描述】:

我在 Node JS 中有一个简单的类

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 objects 的最佳方法是什么,而不是循环检查每个元素的 instanceof

【问题讨论】:

  • 您的问题不清楚。 check if this array is instanceof Animal objects 你是说check if this array only contains instanceof Animal objects 吗?
  • @ikhvjs:没错!
  • 那么,你仍然需要遍历数组中的所有元素进行检查。

标签: javascript node.js ecmascript-6 es6-class


【解决方案1】:

使用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));

【讨论】:

  • 为了清楚起见,这仍然会遍历数组中的每个项目
  • 确实,没有循环是不可能的
猜你喜欢
  • 2015-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多