打乱数组顺序

/**
* 打乱数组顺序
* @param {Array} array
* @returns
*/
function array_shuffle(array) {
let array_ = [...array];
array_.sort(() => {
return 0.5 - Math.random();
});
return array_;
}

let arr = ['a', 'b', 'c', 'd', 'e'];
console.log(array_shuffle(arr));
// [ 'b', 'c', 'd', 'a', 'e' ]

从数组中随机选择一个值

/**
* 从数组中随机选择一个值
* @param {Array} array
* @returns
*/
function array_random(array) {
return array[Math.floor(Math.random() * array.length)];
}

let arr = ['a', 'b', 'c', 'd', 'e'];
console.log(array_random(arr));
// d

删除数组重复的元素

/**
* 删除数组重复的元素
* @param {Array} array
* @returns
*/
function array_unique(array) {
return [...new Set(array)];
}

let arr = ['a', 'b', 'a', 'd', 'd'];
console.log(array_unique(arr));
// [ 'a', 'b', 'd' ]
/**
* 过滤数组中值为 false 的值
* @param {Array} array
* @returns
*/
function array_filter_empty(array) {
return array.filter(Boolean)
}

let arr = [0, 1 , null, undefined];

console.log(array_filter_empty(arr));
// [ 1 ]

清空数组

// 方式一:
let arr = [1, 2, 3];

arr.length = 0;

console.log(arr);
// []


// 方式二:
let arr = [1, 2, 3];

arr.splice(0, arr.length);

console.log(arr);
// []

反转字符串

/**
* 反转字符串
* @param {String} str
* @returns
*/
function reverse_string(str) {
return str.split("").reverse().join("");
}

let str = 'hello wordl';
console.log(reverse_string(str));
// ldrow olleh


参考
​强推:20个值得收藏的ES6小技巧​