Typescript Swap Elements

how to replace two elements with typescript

elements:elements[] =[];
elements.push(item1);
elements.push(item2);
elements.push(item3);
elements.push(item4);


elements[0] is item1 
elements[3] is item4

How can I exchange these elements in typescript. I know a Javascript method, for example:

* javascript example using a temporary variable *

var tmp = elements[0];
elements[0] = elements[3];
elements[3] = tmp;

but there is an api doing the same thing in typescript as  array.swap()

+4
source share
4 answers

There are no built-in functions, but you can easily add it:

interface Array<T> {
    swap(a: number, b: number): void;
}

Array.prototype.swap = function (a: number, b: number) {
    if (a < 0 || a >= this.length || b < 0 || b >= this.length) {
        return
    }

    const temp = this[a];
    this[a] = this[b];
    this[b] = temp;
}

( code on the playground )

If you use modules, you need to do this to increase the interface Array:

declare global {
    interface Array<T> {
        swap(a: number, b: number): void;
    }
}
+3
source

.

[elements[0], elements[3]] = [elements[3], elements[0]];
+10
swapArray(Array:any,Swap1:number,Swap2:number) : any
{
    var temp = Array[Swap1];
    Array[Swap1] = Array[Swap2]
    Array[Swap2] = temp
    return Array;
}
+2

Javascript (, , Typescript, Typescript , ).

(, , ) , a b (credit ):

a = [b, b=a][0];

, 3 , : = [ '', '', '']

"" "" :

a = [a[1],a[1]=a[0],a[2]]

, OP 4, (0-) () , :

elements = [elements[3],elements[1],elements[2],elements[3]=elements[0]]

, . tmp . , , .

0
source

Source: https://habr.com/ru/post/1660375/


All Articles