繁体   English   中英

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

[英]How to declare array of specific type in javascript

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

类似var arr: Array(int)会很好......

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

打字稿中特定类型的数组

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

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

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

}

首先,我对我的英语感到抱歉。 我不擅长。

这不是 JavaScript 的官方做法。 因为它的工作原理是初始化一个包含特定数据类型元素的数组对象。 默认情况下,JavaScript 会理解数组具有该数据类型。 然后我们将删除该元素,我们可以使用具有特定数据类型的数组。

您可以使用这种方式在 JavaScript 中声明具有特定类型的数组

let array = new Array(int);
array.pop();

array.push(1);
array.push(2);
array.push(3);

array.forEach(element => console.log(element));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM