copyWithin.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var isArray = require('./isArray')
  2. /**
  3. * 浅复制数组的一部分到同一数组中的另一个位置,数组大小不变
  4. *
  5. * @param {Array} array 数组
  6. * @param {Number} target 从该位置开始替换数据
  7. * @param {Number} start 从该位置开始读取数据,默认为 0 。如果为负值,表示倒数
  8. * @param {Number} end 到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数
  9. * @return {Array}
  10. */
  11. function copyWithin (array, target, start, end) {
  12. if (isArray(array) && array.copyWithin) {
  13. return array.copyWithin(target, start, end)
  14. }
  15. var replaceIndex, replaceArray
  16. var targetIndex = target >> 0
  17. var startIndex = start >> 0
  18. var len = array.length
  19. var endIndex = arguments.length > 3 ? end >> 0 : len
  20. if (targetIndex < len) {
  21. targetIndex = targetIndex >= 0 ? targetIndex : len + targetIndex
  22. if (targetIndex >= 0) {
  23. startIndex = startIndex >= 0 ? startIndex : len + startIndex
  24. endIndex = endIndex >= 0 ? endIndex : len + endIndex
  25. if (startIndex < endIndex) {
  26. for (replaceIndex = 0, replaceArray = array.slice(startIndex, endIndex); targetIndex < len; targetIndex++) {
  27. if (replaceArray.length <= replaceIndex) {
  28. break
  29. }
  30. array[targetIndex] = replaceArray[replaceIndex++]
  31. }
  32. }
  33. }
  34. }
  35. return array
  36. }
  37. module.exports = copyWithin