将true类型作为参数传递给JavaScript中的方法

Pass the true type as a parameter to a method in JavaScript

本文关键字:JavaScript 方法 参数传递 true 类型      更新时间:2023-09-26

我在JavaScript中有以下代码,其中我的目标是返回与为参数objectType传递的类型匹配的所有对象。我尝试为objectType传递一个字符串,如PersonEmployee,但随后instanceof运算符抛出一个错误,称为expecting a function in instanceof check

问题:在下面的方法中,用JavaScript传递对象类型作为参数的正确方法是什么?此代码的演示不起作用,位于以下URL:此的演示

function getObjectsOfType(allObjects, objectType) {
var objects = [];
 for (var i = 0; i < allObjects.length; i++) {
    if (allObjects[i] instanceof objectType) {
        objects.push(allObjects[i]);
    }
 }
 return objects;
}
//CALL to ABOVE Method which throws an error
var personObjects = getObjectsOfType( allObjects, "Person");
var employeeObjects = getObjectsOfType( allObjects, "Employee");
//Person object constructor
function Person(fullname, age, city) {
  this.fullName = fullname;
  this.age = age;
  this.city = city;
}
//Employee object constructor
function Employee(fullname, age, position, company) {
  this.fullName = fullname;
  this.age = age;
  this.position = position;
  this.company = company;
}

好吧,instanceof有一个问题,它不适用于基元(请参阅如何在JavaScript中获得对象类型的名称?)

有对象的东西要好得多,你应该只通过没有""的人

var personObjects = getObjectsOfType( allObjects, Person);