如何在javascript中声明特定类型的数组
在java脚本中,是否可以显式地将数组声明为int(或任何其他类型)数组 像如何在javascript中声明特定类型的数组,javascript,arrays,types,declaration,strict,Javascript,Arrays,Types,Declaration,Strict,在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 ex
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
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
导出类组件
{
genders=新数组();
装货性别()
{
this.genders.push({name:“Male”,等码:1});
this.genders.push({name:“FeMale”,等码:2});
}
}
类型GenderType={name:string,isoCode:number};//指定格式
首先,我对我的英语很抱歉。我不擅长
这不是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));
如果只是想限制用户根据输入的第一个值推送值,可以使用下面的代码
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(但是类型检查只在编译时发生)。您需要它做什么?如果您正在研究类型安全性,请查看可能可用的,具体取决于您针对的浏览器。但是,它们不能是任何类型的