UNPKG

@buession/prototype

Version:

A native object extension framework for Javascript.

110 lines (109 loc) 2.31 kB
"use strict"; /** * Array 对象扩展 */ /** * 判断数组是否为空数组 * * @return boolean */ Array.prototype.isEmpty = function () { return this.length === 0; }; /** * 判断元素是否在数组中 * * @param item 查找对象 * @return boolean */ Array.prototype.exists = function (item) { return this.indexOf(item) !== -1; }; /** * 获取一个元素 * * @return 第一个元素 */ Array.prototype.first = function () { if (this.length === 0) { throw "Array index out of range: 0"; } return this[0]; }; /** * 获取一个元素 * * @return 第一个元素 */ Array.prototype.last = function () { if (this.length === 0) { throw "Array index out of range: 0"; } return this[this.length - 1]; }; /** * 数组迭代 * * @param callback 回调函数 * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ Array.prototype.each = Array.prototype.forEach; /** * 获取数组大小 * * @return 数组大小 */ Array.prototype.size = function () { return this.length; }; /** * 克隆数组 * * @return 克隆结果 */ Array.prototype.merge = Array.prototype.concat; /** * 返回一个不包含 null/undefined 值元素的数组的新版本 * * @return 不包含 null/undefined 值元素的数组的新版本 */ Array.prototype.compact = function () { return this.filter(value => Object.isUndefinedOrNull(value) === false); }; /** * 对数组的元素进行去重 * * @return 数组元素进行去重后的新版本 */ Array.prototype.unique = function () { return Array.from(new Set(this)); }; /** * 返回不包括参数中任意一个指定值的数组 * * @param values 排除值数组 * @return 不包括参数中任意一个指定值的数组 */ Array.prototype.without = function () { for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) { values[_key] = arguments[_key]; } return this.filter(value => values.includes(value) === false); }; /** * 克隆数组 * * @return 克隆结果 */ Array.prototype.clone = function () { return this.slice(0); }; /** * 清空数组 * * @return 空数组 */ Array.prototype.clear = function () { this.length = 0; return this; };