如何在JavaScript中声明特定类型的数组

14

在 JavaScript 中,是否可以明确声明一个数组为 int 类型的数组(或其他类型)?

类似 var arr: Array(int) 这样的语法会很好...


5
不。JavaScript 是动态类型语言。你可以考虑使用类似 TypeScript 这样的语言进行静态类型检查,并将其编译为原生 JavaScript(类型检查只在编译时进行)。 - Matt Burland
1
你为什么需要它?如果你正在寻找类型安全方面的解决方案,可以看一下http://www.typescriptlang.org/。 - Bergi
1
根据您的目标浏览器,可能会提供Typed arrays,但它们不能是任何类型。 - Frédéric Hamidi
3个回答

9
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]
   }
}

编辑:按以下方式使用

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'之类的操作,则抛出异常呢? - Trashman

2

Typescript中特定类型的数组

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

4
好的,我可以帮忙翻译 JavaScript 相关的问题。请提供需要翻译的具体内容。 - alfoks

0

如果你只想限制用户按照第一个输入的值推送值,你可以使用以下代码

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);
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接