原文请移步


getter源码解读

  1. var REG_KEY = /\[(['"_a-zA-Z0-9]*)\]|\./gi;
  2. /**
  3. * getter
  4. * @param {object} data the object data
  5. * @param {string} path the key path you want to get
  6. * @param {object} options another options
  7. */
  8. function getter(data, path) {
  9. // 处理是不是有第三个参数
  10. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  11. // 这里使用这个正则 让path由字符串转为 [],调用这个正则会使数组中出现 undefined(搞不懂为什么这么处理);
  12. // 如 data为{a:{b:{c:c}}}, path为'a.b.c' ==> 此处path.split(REG_KEY)返回的是[a,undefined,b,undefined,c];
  13. // 然后经 filter 处理后 pathArr为[a,b,c]
  14. var pathArr = path.split(REG_KEY).filter(function (item) {
  15. return !!item;
  16. });
  17. var result = pathArr.reduce(function (result, currentPath, currentIndex) {
  18. // 如果 当前遍历的第一项有不为 null 的 errorPath,则继续进行
  19. if (!result.errorPath) {
  20. // get value
  21. // 将 currentPath([a,b,c]中的每一项)中的 ' 或 "通过正则去掉;
  22. var key = currentPath.replace(/[\'\"]/gi, '');
  23. // 给当前项的 value 重新赋值,从而实现一层一层的验证 正确性
  24. result.value = result.value[key];
  25. // check value
  26. // 通过 currentIndex !== pathArr.length - 1 判断是不是最后一项,是的话,说明data没问题,不走下面逻辑
  27. if (currentIndex !== pathArr.length - 1) {
  28. // can not get the next value
  29. var currentValueType = Object.prototype.toString.call(result.value);
  30. // 此方法只支持 数组 和对象,如果有一层为 字符串、数字、布尔、null、undefined则应该抛错
  31. if (/String|Number|Boolean|Null|Undefined/.test(currentValueType)) {
  32. result.errorPath = currentPath;
  33. }
  34. }
  35. }
  36. return result;
  37. // { value: data, errorPath: null } 为reduce 中的第一项,即为我们要验证的 那个 data({a:{b:{c:'c'}}})
  38. }, { value: data, errorPath: null });
  39. // throw error
  40. if (options.errorCallback && Object.prototype.toString.call(options.errorCallback) === '[object Function]') {
  41. options.errorCallback(result.errorPath, pathArr);
  42. }
  43. return result.value;
  44. }

注: !!item —> 将!!右边的值 转化为 布尔值


以上代码核心原理:

  1. // 柯理化前
  2. const get = (p, o) =>
  3. p.reduce((xs, x) =>
  4. (xs && xs[x]) ? xs[x] : null, o)
  5. // 柯理化后
  6. const get = p => o =>
  7. p.reduce((xs, x) =>
  8. (xs && xs[x]) ? xs[x] : null, o)

柯理化的好处:

  1. const getUserComments = get(['user', 'posts', 0, 'comments'])
  2. console.log(getUserComments(props))
  3. // [ 'Good one!', 'Interesting...' ]
  4. console.log(getUserComments({user:{posts: []}}))
  5. // null