clear.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var helperDeleteProperty = require('./helperDeleteProperty')
  2. var isPlainObject = require('./isPlainObject')
  3. var isObject = require('./isObject')
  4. var isArray = require('./isArray')
  5. var isNull = require('./isNull')
  6. var assign = require('./assign')
  7. var objectEach = require('./objectEach')
  8. /**
  9. * 清空对象
  10. *
  11. * @param {Object} obj 对象
  12. * @param {*} defs 默认值,如果不传(清空所有属性)、如果传对象(清空并继承)、如果传值(给所有赋值)
  13. * @param {Object/Array} assigns 默认值
  14. * @return {Object}
  15. */
  16. function clear (obj, defs, assigns) {
  17. if (obj) {
  18. var len
  19. var isDefs = arguments.length > 1 && (isNull(defs) || !isObject(defs))
  20. var extds = isDefs ? assigns : defs
  21. if (isPlainObject(obj)) {
  22. objectEach(obj, isDefs ? function (val, key) {
  23. obj[key] = defs
  24. } : function (val, key) {
  25. helperDeleteProperty(obj, key)
  26. })
  27. if (extds) {
  28. assign(obj, extds)
  29. }
  30. } else if (isArray(obj)) {
  31. if (isDefs) {
  32. len = obj.length
  33. while (len > 0) {
  34. len--
  35. obj[len] = defs
  36. }
  37. } else {
  38. obj.length = 0
  39. }
  40. if (extds) {
  41. obj.push.apply(obj, extds)
  42. }
  43. }
  44. }
  45. return obj
  46. }
  47. module.exports = clear