TypeScript中实现swap
需要交换数组中的数据,想到C++,有swap方法,于是想要看看TypeScript中有没有。
let arr=[1,2,3,4,5,6,7];
1
期望输出结果为[1,3,2,4,5,6,7]
目前找到三种实现方法,下面分享给大家。
一种是创建临时变量,进行交换。
/**
* 数组中元素交换
* @param arr 数组
* @param a 交换下标
* @param b 交换下标
*/
function swap<T>(arr:T[],a:number,b:number){
let temp=arr[a];
arr[a]=arr[b];
arr[b]=temp
}
swap(arr,1,2);
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
第二种是修改Array原型。
需要注意的是:however, be aware that this is generally a bad pattern to avoid (since this can create issues when multiple different libraries have different ideas of what belongs in the builtin types)
如果多个不同的库对内置类型的内容有不同的操作时,这会产生问题。
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;
}
arr.swap(1,2);
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
第三种为TypeScript的解构
// swap variables
// [first, second] = [second, first];
[arr[1],arr[2]]=[arr[2],arr[1]];
1
2
3
2
3
大家根据自己的喜好使用,我用的是第三种😁
附上参考链接:
https://stackoverflow.com/questions/40523934/typescript-swap-array-items
https://stackoverflow.com/questions/4011629/swapping-two-items-in-a-javascript-array
上次更新: 2020/10/21, 11:10:06