【问题标题】:How to declare array of specific type in javascript如何在javascript中声明特定类型的数组
【发布时间】:2014-04-14 13:26:16
【问题描述】:

是否可以在 java 脚本中将数组显式声明为 int(或任何其他类型)数组?

var arr: Array(int) 这样的东西会很好......

【问题讨论】:

  • 没有。 Javascript是动态类型的。您可以查看 typescript 之类的东西,它可以是静态类型的,并且会编译为 vanilla javascript(但是类型检查只发生在编译时)。
  • 你需要这个做什么?如果您正在研究类型安全,请查看 typescriptlang.org
  • Typed arrays 可能可用,具体取决于您定位的浏览器。但是,它们不能是任何类型。

标签: javascript arrays types declaration strict


【解决方案1】:
var StronglyTypedArray=function(){
      this.values=[];
      this.push=function(value){
      if(value===0||parseInt(value)>0) this.values.push(value);
      else return;//throw exception
     };
     this.get=function(index){
        return this.values[index]
     }
   }

EDITS:如下使用它

     var numbers=new StronglyTypedArray();
     numbers.push(0);
     numbers.push(2);
     numbers.push(4);
     numbers.push(6);
     numbers.push(8);
     alert(numbers.get(3)); //alerts 6

【讨论】:

  • 这在调用push 向动态数组添加值时起作用。但是,如果您想防止分配错误的类型怎么办?例如,numbers[0] = 0; numbers[1] = 2 分配前两个,然后如果有人尝试执行 numbers[2]='hello' 则抛出异常?
【解决方案2】:

打字稿中特定类型的数组

export class RegisterFormComponent 
{
     genders = new Array<GenderType>();

     loadGenders()
     {
        this.genders.push({name: "Male",isoCode: 1});
        this.genders.push({name: "FeMale",isoCode: 2});
     }

}

type GenderType = { name: string, isoCode: number };    // Specified format

【讨论】:

  • 问题是关于javascript的
【解决方案3】:

如果您只是想限制用户根据输入的第一个值推送值,您可以使用以下代码

var stronglyTypedArray =  function(type) {
this.values = [];
this.typeofValue;
this.push = function(value) {
   if(this.values.length === 0) {
     this.typeofValue = typeof value;
     this.pushValue(value);
     return;   
   }
    if(this.typeofValue === typeof value) {
       this.pushValue(value);
    } else {
        alert(`type of value should be ${this.typeofValue}`)
    }
}

this.pushValue = function(value) {
     this.values.push(value);
}

}

如果要传递自己的类型,可以将上面的代码稍微自定义一下

var stronglyTypedArray =  function(type) {
this.values = [];
this.push = function(value) {
    if(type === typeof value) {
       this.pushValue(value);
    } else {
        alert(`type of value should be ${type}`)
    }
}

this.pushValue = function(value) {
     this.values.push(value);
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2022-08-10
    相关资源
    最近更新 更多