utils.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict'
  2. // utils is a library of generic helper functions non-specific to axios
  3. var toString = Object.prototype.toString
  4. /**
  5. * Determine if a value is an Array
  6. *
  7. * @param {Object} val The value to test
  8. * @returns {boolean} True if value is an Array, otherwise false
  9. */
  10. export function isArray (val) {
  11. return toString.call(val) === '[object Array]'
  12. }
  13. /**
  14. * Determine if a value is an Object
  15. *
  16. * @param {Object} val The value to test
  17. * @returns {boolean} True if value is an Object, otherwise false
  18. */
  19. export function isObject (val) {
  20. return val !== null && typeof val === 'object'
  21. }
  22. /**
  23. * Determine if a value is a Date
  24. *
  25. * @param {Object} val The value to test
  26. * @returns {boolean} True if value is a Date, otherwise false
  27. */
  28. export function isDate (val) {
  29. return toString.call(val) === '[object Date]'
  30. }
  31. /**
  32. * Determine if a value is a URLSearchParams object
  33. *
  34. * @param {Object} val The value to test
  35. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  36. */
  37. export function isURLSearchParams (val) {
  38. return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams
  39. }
  40. /**
  41. * Iterate over an Array or an Object invoking a function for each item.
  42. *
  43. * If `obj` is an Array callback will be called passing
  44. * the value, index, and complete array for each item.
  45. *
  46. * If 'obj' is an Object callback will be called passing
  47. * the value, key, and complete object for each property.
  48. *
  49. * @param {Object|Array} obj The object to iterate
  50. * @param {Function} fn The callback to invoke for each item
  51. */
  52. export function forEach (obj, fn) {
  53. // Don't bother if no value provided
  54. if (obj === null || typeof obj === 'undefined') {
  55. return
  56. }
  57. // Force an array if not already something iterable
  58. if (typeof obj !== 'object') {
  59. /*eslint no-param-reassign:0*/
  60. obj = [obj]
  61. }
  62. if (isArray(obj)) {
  63. // Iterate over array values
  64. for (var i = 0, l = obj.length; i < l; i++) {
  65. fn.call(null, obj[i], i, obj)
  66. }
  67. } else {
  68. // Iterate over object keys
  69. for (var key in obj) {
  70. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  71. fn.call(null, obj[key], key, obj)
  72. }
  73. }
  74. }
  75. }
  76. /**
  77. * 是否为boolean 值
  78. * @param val
  79. * @returns {boolean}
  80. */
  81. export function isBoolean(val) {
  82. return typeof val === 'boolean'
  83. }