Typescript交换数组项 [英] Typescript swap array Items

查看:1222
本文介绍了Typescript交换数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 typescript

how to swap two elements using typescript

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


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

我如何 交换 typescript 中的这些项目。我知道Javascript方式,如下所示:

How can i interchange these items in typescript. i know Javascript way, like this:

* javascript示例使用临时变量*

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

但是 typescript <中有任何api做同样的事情/ strong>喜欢
array.swap()

推荐答案

它没有内置功能,但您可以轻松添加它:

There's no builtin functionality for it, 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;
}

游乐场代码

如果您正在使用模块,那么您需要这样做以扩充数组界面:

If you are using modules then you'll need to do this to augment the Array interface:

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

这篇关于Typescript交换数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆