【问题标题】:JS typeOf(array) = 'object' [duplicate]JS typeOf(array) = 'object' [重复]
【发布时间】:2020-02-12 12:40:18
【问题描述】:

我对 JS 的 typeOf 是如何工作的感到困惑。

我有一个带有属性数组的 ES6 类。

当我 console.log 这个属性时,它显示'object'。

class Team extends Model {
  constructor(view){
    super(config.saveName + ' Team');
    this.members = [];   // Clearly an array.
  }

  addPerson(person){
    this.members.push(person);
    this.emit('personAdded', person);
  }

  removePerson(person){
    if(this.members.includes(person)){
        this.members.splice(this.members.indexOf(person),1);
        this.emit('personRemoved', person);
    }
  }

  update(newTeam){
    this.members = newTeam;
    this.emit('teamDataChanged', this.members);
  }
}

console.log(typeOf(new Team().members)); // 'object'

【问题讨论】:

  • JavaScript 不是强类型的。到底JS中的Array也是一个对象
  • 两个阅读建议:About object AND JS Data Types
  • 好吧,我记得我读过这个。唔。问题是我想使用 AppML 在 html 中显示数组。那么如何从对象属性中创建一个数组呢?我知道它通过制作一个对象文字来工作。但是这里我有一个类实例。

标签: javascript arrays object typeof


【解决方案1】:

在 JS 中,除了原语之外的一切都是对象。原语是 : 数字 , 布尔值 , 空值 , 不明确的 , 细绳 , 符号

其余的是对象(数组、对象、映射、集合...)

所以typeof [] === "Object"typeof 123 === "number"

【讨论】:

  • 嗯,恕我直言,没有null的类型
  • @messerbill:Null 和 Undefined 都是具有单个值的数据类型。不过typeof 的行为相对随意。
  • 这不是“那么”简单/直截了当。值得注意的异常值是typeof nulltypeof function(){}。是的,JavaScript 有这些数据类型,但typeof 本身与它们并不完全一致。
  • console.log(typeof null) 返回“对象”。 (这对我来说真的没有意义)
  • @LukStorms:这可能是有原因的,但 typeof 运算符实际上只是一个大查找表:ecma-international.org/ecma-262/6.0/#sec-typeof-operator
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2012-10-11
相关资源
最近更新 更多