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
Answer from Bellash on Stack OverflowVideos
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
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
Yes you can type your variables with a single type
// type data as an array of strings
const data: string[] = [];
// type data as an array of numbers
const data: number[] = [];
// type data as an array of objects
const data: object[] = [];
If you want to use a mix of types in your array, you can type it as any. But this may not be a good practise.
const data: any[] = [];
For more information about type in typescript, look here: Basic type documentation
For defining array with multiple types, look here: https://stackoverflow.com/a/29382420/1934484
You can define your array like this the typescript compiler will only allow strings
const array: Array<string> = [];
or if you want to have strings and numbers define it like this
const array: Array<string | number> = [];
You can also define it this way
const array: string[] = [];
const array: (string | number)[] = [];
In ES6 using Array from() and keys() methods.
Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Shorter version using spread operator.
[...Array(10).keys()]
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Start from 1 by passing map function to Array from(), with an object with a length property:
Array.from({length: 10}, (_, i) => i + 1)
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You can do so:
var N = 10;
Array.apply(null, {length: N}).map(Number.call, Number)
result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
or with random values:
Array.apply(null, {length: N}).map(Function.call, Math.random)
result: [0.7082694901619107, 0.9572225909214467, 0.8586748542729765, 0.8653848143294454, 0.008339877473190427, 0.9911756622605026, 0.8133423360995948, 0.8377588465809822, 0.5577575915958732, 0.16363654541783035]
Explanation
First, note that Number.call(undefined, N) is equivalent to Number(N), which just returns N. We'll use that fact later.
Array.apply(null, [undefined, undefined, undefined]) is equivalent to Array(undefined, undefined, undefined), which produces a three-element array and assigns undefined to each element.
How can you generalize that to N elements? Consider how Array() works, which goes something like this:
function Array() {
if ( arguments.length == 1 &&
'number' === typeof arguments[0] &&
arguments[0] >= 0 && arguments &&
arguments[0] < 1 << 32 ) {
return [ … ]; // array of length arguments[0], generated by native code
}
var a = [];
for (var i = 0; i < arguments.length; i++) {
a.push(arguments[i]);
}
return a;
}
Since ECMAScript 5, Function.prototype.apply(thisArg, argsArray) also accepts a duck-typed array-like object as its second parameter. If we invoke Array.apply(null, { length: N }), then it will execute
function Array() {
var a = [];
for (var i = 0; i < /* arguments.length = */ N; i++) {
a.push(/* arguments[i] = */ undefined);
}
return a;
}
Now we have an N-element array, with each element set to undefined. When we call .map(callback, thisArg) on it, each element will be set to the result of callback.call(thisArg, element, index, array). Therefore, [undefined, undefined, …, undefined].map(Number.call, Number) would map each element to (Number.call).call(Number, undefined, index, array), which is the same as Number.call(undefined, index, array), which, as we observed earlier, evaluates to index. That completes the array whose elements are the same as their index.
Why go through the trouble of Array.apply(null, {length: N}) instead of just Array(N)? After all, both expressions would result an an N-element array of undefined elements. The difference is that in the former expression, each element is explicitly set to undefined, whereas in the latter, each element was never set. According to the documentation of .map():
callbackis invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Therefore, Array(N) is insufficient; Array(N).map(Number.call, Number) would result in an uninitialized array of length N.
Compatibility
Since this technique relies on behaviour of Function.prototype.apply() specified in ECMAScript 5, it will not work in pre-ECMAScript 5 browsers such as Chrome 14 and Internet Explorer 9.
Here is a simple solution that works in codepen:
Array.from(Array(10).keys())
To be clear, Array.from() and Array.keys() require an ES6 polyfill in order to work in all browsers.
A tour of Array.from thru practical examples
Array.from also accepts a second argument which is used as a mapping function
let out = Array.from(Array(10), (_,x) => x);
console.log(out);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This is nice to know because you might want to generate arrays that are sometimes more complex than just 0 thru N.
const sq = x => x * x;
let out = Array.from(Array(10), (_,x) => sq(x));
console.log(out);
// [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Or you can make arrays out of generators, too
function* range(start, end, step) {
while (start < end) {
yield start;
start += step;
}
}
let out = Array.from(range(10,20,2));
console.log(out); // [10, 12, 14, 16, 18]
Array.from is just massively powerful. People don't even realize its full potential yet.
const ord = x => x.charCodeAt(0);
const dec2hex = x => `0${x.toString(16)}`.substr(-2);
// common noob code
{
let input = "hello world";
let output = input.split('').map(x => dec2hex(ord(x)));
console.log(output);
// ["68", "65", "6c", "6c", "6f", "20", "77", "6f", "72", "6c", "64"]
}
// Array.from
{
let input = "hello world";
let output = Array.from(input, x => dec2hex(ord(x)));
console.log(output);
// ["68", "65", "6c", "6c", "6f", "20", "77", "6f", "72", "6c", "64"]
}