UNPKG

native-class-ext

Version:

js原生对象增加常用方法

117 lines (108 loc) 3.03 kB
(function(){ const defineProperty = require('./defineProperty.js') /** * 对Array类进行扩展 * @author gwl * @since 2020年4月29日13:04:41 * */ /** * 根据位置删除 * @param {Numbar} index 删除的位置0开始 * @return {Array} 删除的值 * */ defineProperty(Array.prototype, '$removeByIndex', function(index){ return this.splice(index, 1); }); /** * 根据值删除 * @param {Object} val 要删除的值 * @param {function} key 数组中对象的key * @return {Array} 删除的值 * */ defineProperty(Array.prototype, '$remove', function(val, key){ let index = this.$findIndex(val, key); if(index < 0){ return []; } return this.$removeByIndex(index); }); /** * 不存在添加,存在删除 * @param {Object} val 要添加或删除的值 * @param {Boolean} padStart 是否添加到开头 * @param {String} key 数组中对象的key * @return {Boolean} 添加返回true * */ defineProperty(Array.prototype, '$addOrRemove', function(val, padStart=false, key){ if(typeof padStart != 'boolean'){ key = padStart; padStart = false; } let tempVal = val; if(typeof key == 'string') { tempVal = val[key]; } let index = this.$findIndex(tempVal, key); if(index < 0){ if(padStart){ this.unshift(val); } else { this.push(val); } return true; } this.$removeByIndex(index); return false; }); /** * 替换 * @param {Number} index 位置,0开始 * @param {Object} value 值 * @return {Array} 旧的值 * */ defineProperty(Array.prototype, '$replace', function(index, value){ return this.splice(index, 1, value); }); /** * 查找数组中的指定元素 * [{name:'aa'}, {name:'bb'}].$findIndex('bb', 'name') = 1; * [{name:'aa'}, {name:'bb'}].$findIndex(null, v=>v.name=='bb') = 1; * [{name:'aa'}, 'bb'].$findIndex('bb') = 1; * */ defineProperty(Array.prototype, '$findIndex', function(value, key){ if(typeof key == 'string') { return this.findIndex(v=>v[key]==value); } else if(typeof key == 'function') { return this.findIndex(key); } else { return this.indexOf(value) } }); /** * 根据值查找 * @param {*} value 要查找的值 * @param {String} key 数组中对象的key * */ defineProperty(Array.prototype, '$findEl', function(value, key){ let index = this.$findIndex(value, key); return this[index] }); // 数组最后一个元素 defineProperty(Array.prototype, '$last', function(){ return this[this.length-1]; }); /** * 交换指定位置的值 * @param {Number} index1 位置 * @param {Number} index2 位置 * */ defineProperty(Array.prototype, '$swap', function (index1, index2){ let temp = this[index1] this[index1] = this[index2]; this[index2] = temp; }); defineProperty(Array, '$isEmpty', function (arg){ if(!Array.isArray(arg) || arg.length==0) return true; return false; }); })()