javascript 如何在javascript中声明特定类型的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23061379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare array of specific type in javascript
提问by 31415926
Is it possible in java script to explicitly declare array to be an array of int(or any other type)?
是否可以在 java 脚本中将数组显式声明为 int(或任何其他类型)的数组?
something like var arr: Array(int)
would be nice...
像var arr: Array(int)
这样的东西会很好......
采纳答案by Bellash
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: use this as follows
编辑:按如下方式使用
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
回答by Mark Macneil Bikeio
Array of specific type in 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
回答by Daomtthuan
Firstly, I'm sorry about my English. I'm not good at it.
首先,我很抱歉我的英语。我不擅长。
This is not the official way of doing in JavaScript. Because it works based on initializing an array object containing an element of a specific data type. By default, JavaScript will understand that array has that data type. Then we will delete that element, we can use the array with the specific data type.
这不是 JavaScript 的官方做法。因为它的工作原理是初始化一个包含特定数据类型元素的数组对象。默认情况下,JavaScript 会理解数组具有该数据类型。然后我们将删除该元素,我们可以使用具有特定数据类型的数组。
You can declare an array with a specific type in JavaScript using this way
您可以使用这种方式在 JavaScript 中声明具有特定类型的数组
let array = new Array(int);
array.pop();
array.push(1);
array.push(2);
array.push(3);
array.forEach(element => console.log(element));