vue中的工具函数

2020/7/21 vue

# inBrowser: 检测当前宿主环境是否是浏览器

// 通过判断 `window` 对象是否存在即可
export const inBrowser = typeof window !== "undefined";
1
2

# hasProto:检查当前环境是否可以使用对象的 __proto__ 属性

// 一个对象的 __proto__ 属性指向了其构造函数的原型
// 从一个空的对象字面量开始沿着原型链逐级检查。
export const hasProto = "__proto__" in {};
1
2
3

# 获取当浏览器的 user Agent

// toLowerCase目的是 为了后续的各种环境检测
export const UA = inBrowser && window.navigator.userAgent.toLowerCase();
1
2

# IE 浏览器判断

export const isIE = UA && /msie|trident/.test(UA);
1

# IE9| Edge | Chrome 判断

export const isIE9 = UA && UA.indexOf("msie 9.0") > 0;
export const isEdge = UA && UA.indexOf("edge/") > 0;
export const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
1
2
3

# isReserved:检测字符串是否以 $ 或者 _ 开头

// charCodeAt() 方法可返回指定位置的字符的 Unicode 编码
export function isReserved(str: string): boolean {
  const c = (str + "").charCodeAt(0);
  return c === 0x24 || c === 0x5f;
}
1
2
3
4
5

# Javascript 中级算法之 charCodeAt

// 从传递进来的字母序列中找到缺失的字母并返回它
function fearNotLetter(str) {
  //将字符串转为ASCII码,并存入数组
  let arr = [];
  for (let i = 0; i < str.length; i++) {
    arr.push(str.charCodeAt(i));
  }
  for (let j = 1; j < arr.length; j++) {
    let num = arr[j] - arr[j - 1];
    //判断后一项减前一项是否为1,若不为1,则缺失该字符的前一项
    if (num != 1) {
      //将缺失字符ASCII转为字符并返回
      return String.fromCharCode(arr[j] - 1);
    }
  }
  return undefined;
}
fearNotLetter("abce"); // "d"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# camelize: 连字符转驼峰

const camelizeRE = /-(\w)/g;
export const camelize = cached(str => {
  return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ""));
});

camelize("aa-bb"); // aaBb
1
2
3
4
5
6

# hyphenate:驼峰转连字符

const hyphenateRE = /\B([A-Z])/g;
export const hyphenate = cached((str: string): string => {
  return str.replace(hyphenateRE, "-$1").toLowerCase();
});
1
2
3
4

# toString: 将给定变量的值转换为 string 类型并返回

function toString(val) {
  return val == null
    ? ""
    : typeof val === "object"
    ? JSON.stringify(val, null, 2)
    : String(val);
}
1
2
3
4
5
6
7

# capitalize:首字符大写

export const capitalize = cached((str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1);
});
1
2
3

# isPrimitive: 判断变量是否为原型类型

export function isPrimitive(value) {
  return (
    typeof value === "string" ||
    typeof value === "number" ||
    typeof value === "symbol" ||
    typeof value === "boolean"
  );
}
1
2
3
4
5
6
7
8

# isRegExp: 判断变量是否为正则对象

const _toString = Object.prototype.toString;
export function isRegExp(v) {
  return _toString.call(v) === "[object RegExp]";
}
1
2
3
4

# isObject: 区分对象和原始值

export function isObject(obj) {
  return obj !== null && typeof obj === "object";
}
1
2
3

# makeMap:判断一个变量是否包含在传入字符串里

function makeMap(str, expectsLowerCase) {
  const map = Object.create(null);
  const list = str.split(",");
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true;
  }
  return expectsLowerCase ? val => map[val.toLowerCase()] : val => map[val];
}

let isMyName = makeMap("abc,hello", true);
console.log(isMyName("hello")); // true
console.log(isMyName("abc")); // true
console.log(isMyName("bcd")); // undefined
1
2
3
4
5
6
7
8
9
10
11
12
13

# once:只调用一次的函数

export function once(fn) {
  let called = false;
  return function() {
    if (!called) {
      called = true;
      fn.apply(this, arguments);
    }
  };
}
1
2
3
4
5
6
7
8
9

# cache:创建一个缓存函数

/**
 * Create a cached version of a pure function.
 */
function cached(fn) {
  const cache = Object.create(null);
  return function cachedFn(str) {
    const hit = cache[str];
    return hit || (cache[str] = fn(str));
  };
}

let ca = cached(function(str) {
  return `ca: ${str}`;
});
console.log(ca("ac-ae"));
console.log(ca("ac-ae"));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16