首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript:确定作为参数传递时的原语类型

Javascript:确定作为参数传递时的原语类型
EN

Stack Overflow用户
提问于 2018-05-31 17:12:50
回答 1查看 19关注 0票数 0

我还尝试了typeof item.type === '<type>' instanceof none,它的工作效果与预期一致。

背景:我正在构建一个表单生成器(使用VueJS)。

这是表单定义:

代码语言:javascript
复制
formDesc: {
        inline: true,
        columns: 2,
        labels: 'top',
        disabled: false,
        fields: [
          {type: Array, prop: 'aprovalStatus', list: ['Pending', 'Rejected', 'Conditional', 'Approved'], label: 'Status', required: true},
          {type: String, prop: 'remarks', html: true, label: 'Remarks'},
          {type: Date, prop: 'approvalDate', label: 'Approval Date', format: 'DD-MM-YYYY'},
          {type: Number, prop: 'deposit', decimals: 2, label: 'Security Deposit'}
        ]
      }

我遇到的问题是在表单生成器端确定form.fields.<item>.type。参数接收正常。要提供正确的输入类型,我需要知道form item类型是什么!

我有以下方法(从谷歌搜索中的一个):

代码语言:javascript
复制
getType (elem) {
  return Object.prototype.toString.call(elem).slice(8, -1).toLowerCase()
}

当我读到它的时候,它应该返回'number','date‘等等。不管我读到了什么,它也会像typeof item.type一样返回'function’。

Source article

在表单生成器代码中,我有确定类型的方法:

代码语言:javascript
复制
...
    check (item) {
      if (item && item.type) {
        console.log('getType = ', this.getType(item.type))
        return true
      } else {
        this.$message({message: 'Field item problem [' + !item ? 'Empty item' : 'no type prop for: ' + (item && item.label ? item.label : 'No label') + ']', type: 'warning'})
        return false
      }

    },

    isArray (item) {
      if (this.check(item) && this.getType(item.type) === 'array' &&
       item.hasOwnProperty('list')) {
        return true
      } else {
        return false
      }
    },
...

isArray, isNumber, is Decimal等用于确定为formDesc.fields中的每个元素显示哪个组件。

我的其他尝试是item.type.constructor === Number

任何链接或解决方案,这是非常感谢。

EN

回答 1

Stack Overflow用户

发布于 2018-05-31 18:35:37

我真傻。这适用于item.type === Number (或相关的原始数据类型)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50620664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档