在 JavaScript 中,是否可以明确声明一个数组为 int 类型的数组(或其他类型)?
类似 var arr: Array(int)
这样的语法会很好...
在 JavaScript 中,是否可以明确声明一个数组为 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
push
将值添加到动态数组时,这很有效。但是,如果您想防止分配错误的类型怎么办?比如说,numbers[0] = 0; numbers[1] = 2
来分配前两个,然后如果有人试图执行numbers[2]='hello'
之类的操作,则抛出异常呢? - TrashmanTypescript中特定类型的数组
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);
}
}