js------数组随机排序和去重

let arr = ['g', 'b', 'c', 'd', 'e', 'a', 'g', 'b', 'c'];

// 数组随机排序(原数组被修改)
Array.prototype.randomSort = function () {
const len = this.length;
for (let i = len - 1; i > 1; i--) {
let n = Math.floor(Math.random() * i);
let lastone = this[i];
this[i] = this[n];
this[n] = lastone;
}
};

// 数组去重(返回新数组)
Array.prototype.removeDuplicate = function () {
let obj = {};
const len = this.length;
for (let i = 0; i<len; i++) {
if (obj[this[i]]) continue;
obj[this[i]] = this[i];
}
return Object.keys(obj);
};

// 用法
arr.removeDuplicate();
arr.randomSort();
posted @ 2019-03-01 11:55  孩子他爹  阅读(553)  评论(0编辑  收藏  举报