ArrayUtils.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /** @format */
  2. interface Array<T> {
  3. /**
  4. * 增删查改
  5. */
  6. updateArrayByOperate(operateArray: any[], operate: number, key: string)
  7. /**
  8. * 根据size分割数组为size份
  9. * @param arr
  10. * @param size
  11. */
  12. splitArrBySize(size: number): any[]
  13. /**
  14. * 打乱顺序
  15. */
  16. outOrder()
  17. }
  18. Array.prototype.updateArrayByOperate = function (operateArray: any[], operate: number, key: string) {
  19. // 1增加 2删除 3修改 4全删
  20. if (operate == 1) {
  21. operateArray.forEach(value => {
  22. this.push(value)
  23. })
  24. } else if (operate == 2) {
  25. operateArray.forEach(value => {
  26. this.splice(
  27. this.findIndex(value1 => value1[key] == value[key]),
  28. 1,
  29. )
  30. })
  31. } else if (operate == 3) {
  32. operateArray.forEach(value => {
  33. this[this.findIndex(value1 => value1[key] == value[key])] = value
  34. })
  35. } else if (operate == 4) {
  36. this.splice(0, this.length)
  37. }
  38. }
  39. Array.prototype.splitArrBySize = function (size: number): any[] {
  40. let arr = []
  41. for (let i = 0; i < this.length; i += size) {
  42. arr.push(this.slice(i, i + size))
  43. }
  44. return arr
  45. }
  46. Array.prototype.outOrder = function () {
  47. this.sort(() => Math.randomRangeFloat(-0.5, 0.5))
  48. }