So I hava array Links and array Params with same langth N
So what I need is to create an object where for each link from Links I will be able to see
param from Params
And than for example to be abble to call something like
for each( item in object)
if (item.param == "some value") {
// some code
} else...
How to do such thing (Code exaMple, please)
From Array: You could first build a list with elements composed of a item and a param (supposing the length is indeed the same for both lists)
var items:Array = new Array();
for(var i:uint = 0; i < links.length; i++) {
links:Array .push({link:links[i], param:params[i]});
}
You can then filter them easily:
items.forEach(checkValue);
for(var i:uint = 0; i < items.length; i++) {
if (items[i].param == "some value") {
// some code
} else{
...
}
}
Related
I'm playing with Typescript and I wonder, how to properly instantiate and declare multidimensional array. Here's my code:
class Something {
private things: Thing[][];
constructor() {
things = [][]; ??? how instantiate object ???
for(var i: number = 0; i < 10; i++) {
this.things[i] = new Thing[]; ??? how instantiate 1st level ???
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing(); ??? how instantiate 2nd lvl item ???
}
}
}
}
Can you give me any hint about selected places?
You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.
The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.
As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.
class Something {
private things: Thing[][];
constructor() {
this.things = [];
for(var i: number = 0; i < 10; i++) {
this.things[i] = [];
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing();
}
}
}
}
Here is an example of initializing a boolean[][]:
const n = 8; // or some dynamic value
const palindrome: boolean[][] = new Array(n)
.fill(false)
.map(() =>
new Array(n).fill(false)
);
If you want to do it typed:
class Something {
areas: Area[][];
constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[] = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}
You can do the following (which I find trivial, but its actually correct).
For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).
Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following
const myArray: any[][] = [];
And later, when you want to populate it, you can do the following:
myArray.push([<your value goes here>]);
A short example of the above can be the following:
const myArray: string[][] = [];
myArray.push(["value1", "value2"]);
Beware of the use of push method, if you don't use indexes, it won't work!
var main2dArray: Things[][] = []
main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)
gives only a 1 line array!
use
main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray
to get your 2d array working!!!
Other beware! foreach doesn't seem to work with 2d arrays!
I’m new to Handlebars.js and just started using it. Most of the examples are based on iterating over an object. I wanted to know how to use handlebars in basic for loop.
Example.
for(i=0 ; i<100 ; i++) {
create li's with i as the value
}
How can this be achieved?
There's nothing in Handlebars for this but you can add your own helpers easily enough.
If you just wanted to do something n times then:
Handlebars.registerHelper('times', function(n, block) {
var accum = '';
for(var i = 0; i < n; ++i)
accum += block.fn(i);
return accum;
});
and
{{#times 10}}
<span>{{this}}</span>
{{/times}}
If you wanted a whole for(;;) loop, then something like this:
Handlebars.registerHelper('for', function(from, to, incr, block) {
var accum = '';
for(var i = from; i < to; i += incr)
accum += block.fn(i);
return accum;
});
and
{{#for 0 10 2}}
<span>{{this}}</span>
{{/for}}
Demo: http://jsfiddle.net/ambiguous/WNbrL/
Top answer here is good, if you want to use last / first / index though you could use the following
Handlebars.registerHelper('times', function(n, block) {
var accum = '';
for(var i = 0; i < n; ++i) {
block.data.index = i;
block.data.first = i === 0;
block.data.last = i === (n - 1);
accum += block.fn(this);
}
return accum;
});
and
{{#times 10}}
<span> {{#first}} {{#index}} {{#last}}</span>
{{/times}}
If you like CoffeeScript
Handlebars.registerHelper "times", (n, block) ->
(block.fn(i) for i in [0...n]).join("")
and
{{#times 10}}
<span>{{this}}</span>
{{/times}}
This snippet will take care of else block in case n comes as dynamic value, and provide #index optional context variable, it will keep the outer context of the execution as well.
/*
* Repeat given markup with given times
* provides #index for the repeated iteraction
*/
Handlebars.registerHelper("repeat", function (times, opts) {
var out = "";
var i;
var data = {};
if ( times ) {
for ( i = 0; i < times; i += 1 ) {
data.index = i;
out += opts.fn(this, {
data: data
});
}
} else {
out = opts.inverse(this);
}
return out;
});
Couple of years late, but there's now each available in Handlebars which allows you to iterate pretty easily over an array of items.
https://handlebarsjs.com/guide/builtin-helpers.html#each
I am currently playing around with flex, I have C++ background, so I am not used to AS3.
The problem is in the main *.mxml file I have fx:script block and I try to define a multidimensional array like that:
public var Board:Array = new Array(25);
I use a function to initialize the 2d-array:
public function initBoard():void {
var i:int;
var j:int;
for (i = 0; i < 25; i++) {
Board[i] = new Array(40);
for (j = 0; i < 40; j++) {
Board[i][j] = 0;
}
}
}
This function gets called later on in the main loop to init and reset the "board" why doesn't it work. The only difference to the AS3 documentation is that it gets done in a function. Is there a scope problem?
Thanking you in anticipation,
Niklas Voss
P.S. I hope someone can tell me why it doesn't work and how to do it right...
You have i where there should be j.
for (j = 0; i < 40; j++) {
This should solve your problems.
for (j = 0; j < 40; j++) {
You don't need to define an array length in AS3 - I just use the [] operator for creating a new array. Also you used i where j was needed in the innermost for loop.
function initBoard():Array
{
var board:Array = [];
var i:int = 0;
var j:int;
for(i; i<25; i++)
{
board[i] = [];
j = 0;
for(j; j<40; j++)
{
board[i][j] = 0;
}
}
return board;
}
trace(initBoard());
I have an array of objects. Each object has a property called name. I want to efficiently remove an object with a particular name from the array. Is this the BEST way?
private function RemoveSpoke(Name:String):void {
var Temp:Array=new Array;
for each (var S:Object in Spokes) {
if (S.Name!=Name) {
Temp.push(S);
}
}
Spokes=Temp;
}
If you are willing to spend some memory on a lookup table this will be pretty fast:
private function remove( data:Array, objectTable:Object, name:String):void {
var index:int = data.indexOf( objectTable[name] );
objectTable[name] = null;
data.splice( index, 1 );
}
The test for this looks like this:
private function test():void{
var lookup:Object = {};
var Spokes:Array = [];
for ( var i:int = 0; i < 1000; i++ )
{
var obj:Object = { name: (Math.random()*0xffffff).toString(16), someOtherProperty:"blah" };
if ( lookup[ obj.name ] == null )
{
lookup[ obj.name ] = obj;
Spokes.push( obj );
}
}
var t:int = getTimer();
for ( var i:int = 0; i < 500; i++ )
{
var test:Object = Spokes[int(Math.random()*Spokes.length)];
remove(Spokes,lookup,test.name)
}
trace( getTimer() - t );
}
myArray.splice(myArray.indexOf(myInstance), 1);
The fastest way will be this:
function remove(array: Array, name: String): void {
var n: int = array.length
while(--n > -1) {
if(name == array[n].name) {
array.splice(n, 1)
return
}
}
}
remove([{name: "hi"}], "hi")
You can also remove the return statement if you want to get rid of all alements that match the given predicate.
I don't have data to back it up but my guess is that array.filter might be the fastest.
In general you should prefer the old for-loop over "for each" and "for each in" and use Vector if your elements are of the same type. If performance is really important you should consider using a linked list.
Check out Grant Skinners slides http://gskinner.com/talks/quick/ and Jackson Dunstan's Blog for more infos about optimization.
If you don't mind using the ArrayCollection, which is a wrapper for the Array class, you could do something like this:
private function RemoveSpoke(Name:String, Spokes:Array):Array{
var ac:ArrayCollection = new ArrayCollection(Spokes);
for (var i:int=0, imax:int=ac.length; i<imax; i++) {
if (Spokes[i].hasOwnProperty("Name") && Spokes[i].Name === Name) {
ac.removeItemAt(i);
return ac.source;
}
}
return ac.source;
}
You could also use ArrayCollection with a filterFunction to get a view into the same Array object
Perhaps this technique (optimized splice method by CJ's) will further improve the one proposed by Quasimondo:
http://cjcat.blogspot.com/2010/05/stardust-v11-with-fast-array-splicing_21.html
Here's an efficient function in terms of reusability, allowing you to do more than remove the element. It returns the index, or -1 if not found.
function searchByProp(arr:Array, prop:String, value:Object): int
{
var item:Object;
var n: int = arr.length;
for(var i:int=n;i>0;i--)
{
item = arr[i-1];
if(item.hasOwnProperty(prop))
if( value == item[prop] )
return i-1;
}
return -1;
}
I'm creating a JsonArray such as:
JsonArray jsonValues = new JsonArray();
for( int i = 0; i < values.Count; i++ )
{
var someSingleValue = values[i];
jsonValues.Add( string.Format( "Name: {0}", someSingleValue ) );
}
After that I'm shipping json values to my javascript in .aspx page via call:
HtmlPage.Window.Invoke("call", jsonValues);
The call works and it gets there, however I have no idea how to iterate over those values, i.e extract them.
I've tried: (in javascript)
for (var x in somevalues){ alert(somevalues); }
I also tried:
for(var i = 0; i < somevalues.length; i++) {
alert(somevalues[i]);
}
but it crashes.(in both cases)
any ideas?
Are you using the eval method to serialize the string to a JSON object?
function call(somevalues){
//somevalues is currently just a string.
var results = eval("(" + somevalues +")");
//results now should contain your array as a JSON object.
//and you should be able to iterate over it at this point.
for(var i = 0; i < results.length; i++){
alert(results[i]);
}
}
Assuming somevalues is truly an array, you do it like this:
for(var i = 0; i < somevalues.length; i++) {
// do something with somevalues[i]
}
What you did was tell JavaScript to iterate over the properties of the somevalues object, which is similar, but not the same, as the iteration using a regular for loop.
EDIT: I am willing to bet your variable, somevalues is a string. Just do alert(somevalues) and see what happens.