JS About

351 阅读1分钟

common use api

effective method

JS特性可选链式操作符 ?.?? 使用

const object = { id: 123, names: { first: 'Alice', last: 'Smith' }};

{ // With optional chaining and nullish coalescing:
  const firstName = object?.names?.first ?? '(no first name)';
  // → 'Alice'

  const middleName = object?.names?.middle ?? '(no middle name)';
  // → '(no middle name)'
}

利用Object.prototype.toString准确判断类

type和instanceof都不能准确判断

var type = function(data) {
      var toString = Object.prototype.toString;
      var dataType =
        data instanceof Element
          ? "element" // 为了统一DOM节点类型输出
          : toString
              .call(data)
              .replace(/\[object\s(.+)\]/, "$1")
              .toLowerCase()
      return dataType
};

js数值精度

数字位数处理

  • 非四舍五入保留2位小数
(Math.floor(x * 100) / 100).toFixed(2); // floor是向下取整,如需四舍五入请使用round
null -> 0.00
undefined -> 0.00
'123' -> 123.00
'1.' -> 1.00
'1.2' -> 1.20
'1.234' -> 1.23
'1.245' -> 1.24
'1.246' -> 1.26

RN for web

Node.js

WebAssembly