Skip to content

js 记录

实现获取 js 数据类型的通用函数

js
const getType = (s) => {
  const r = Object.prototype.toString.call(s)

  return r.replace(/\[object (.*?)\]/, '$1').toLowerCase()
}

// 测试
console.log(getType()) // undefined
console.log(getType(null)) // null
console.log(getType(1)) // number
console.log(getType('前端胖头鱼')) // string
console.log(getType(true)) // boolean
console.log(getType(Symbol('前端胖头鱼'))) // symbol
console.log(getType({})) // object
console.log(getType([])) // array

根据 name 获取 url 上的 search 参数值

js
const getQueryByName = (name) => {
  const queryNameRegex = new RegExp(`[?&]${name}=([^&]*)(&|$)`)
  const queryNameMatch = window.location.search.match(queryNameRegex)
  // 一般都会通过 decodeURIComponent 解码处理
  return queryNameMatch ? decodeURIComponent(queryNameMatch[1]) : ''
}

// https://www.baidu.com/?name=%E5%89%8D%E7%AB%AF%E8%83%96%E5%A4%B4%E9%B1%BC&sex=boy

console.log(getQueryByName('name'), getQueryByName('sex')) // 前端胖头鱼 boy

千分位格式化数字

写一个正则,将数字千分位格式化,并且要支持小数。

js
// 金额转千分位
const formatPrice = (number) => {
  number = '' + number

  const [ integer, decimal = '' ] = number.split('.')

  return integer.replace(/\B(?=(\d{3})+$)/g, ',') + (decimal ? '.' + decimal : '')
}

console.log(formatPrice(123456789.3343)) // 123,456,789.3343

Math.floor、Math.ceil、Math.round 的区别

Math.floor() 函数总是返回小于等于一个给定数字的最大整数,包括负数。

js
console.log(Math.floor(5.95));
// Expected output: 5

console.log(Math.floor(5.05));
// Expected output: 5

console.log(Math.floor(5));
// Expected output: 5

console.log(Math.floor(-5.05));
// Expected output: -6

Math.ceil() 静态方法总是向上舍入(向 x 轴正方向舍入),并返回大于等于给定数字的最小整数,包括负数。

js
console.log(Math.ceil(0.95));
// Expected output: 1

console.log(Math.ceil(4));
// Expected output: 4

console.log(Math.ceil(7.004));
// Expected output: 8

console.log(Math.ceil(-7.004));
// Expected output: -7

Math.round() 函数返回一个数字四舍五入后最接近的整数。

如果参数的小数部分大于 0.5,则舍入到相邻的绝对值更大的整数。如果参数的小数部分小于 0.5,则舍入到相邻的绝对值更小的整数。如果参数的小数部分恰好等于 0.5,则舍入到相邻的在正无穷(+∞)方向上的整数。

逗号表达式的使用

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Comma_Operator

js
const getStoreValue = (which, key) => typeof key === 'string' ? { [key]: store.state[which][key] } : key.reduce((t, i) => (t[i] = store.state[which][i], t), {});

简单来说,逗号表达式的返回值为逗号的最右边值。

js
x = (y = 5, z = 6); // 值 6 返回到控制台
console.log(x); // 6 (right-most)

js 判断变量的类型

使用 typeof 来判断变量的类型。

Type	         Predicate

string	       typeof s === "string"
number	       typeof n === "number"
boolean	       typeof b === "boolean"
undefined	     typeof undefined === "undefined"
function	     typeof f === "function"
array	         Array.isArray(a)

Released under the MIT License.