javascript - Typescript swap array Items -


how swap 2 elements using typescript

elements:elements[] =[]; elements.push(item1); elements.push(item2); elements.push(item3); elements.push(item4);   elements[0] item 1  element[3] item 3 

how can interchange items in typescript, know java script way.like

javascript example

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

but there api doing same thing in typescript array.swap()

there's no builtin functionality it, can add it:

interface array<t> {     swap(a: number, b: number): void; }  array.prototype.swap = function (a: number, b: number) {     if (a < 0 || >= this.length || b < 0 || b >= this.length) {         return     }      const temp = this[a];     this[a] = this[b];     this[b] = temp; } 

(code in playground)

if using modules you'll need augment array interface:

declare global {     interface array<t> {         swap(a: number, b: number): void;     } } 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -