一行代码完成解构加赋值

我们日常经常使用结构赋值,一般都是先结构,再赋值,当然我们也可以一行就完成解构加赋值操作,看起来非常简化,当然可读性你懂得!

let people = { name: null, age: null };
let result = { name: '张三',  age: 16 };

({ name: people.name, age: people.age} = result);
console.log(people) // {"name":"张三","age":16}

对基础数据类型进行解构

日常中我们应该用不到这样的场景,但是实际上我们也可以对基础数据类型解构

const { length : a } = '1234';
console.log(a) // 4

对数组解构快速拿到最后一项值

实际上我们是可以对数组解构赋值拿到length属性的,通过这个特性也可以做更多的事情。

const arr = [1, 2, 3];
const { 0: first, length, [length - 1]: last } = arr;
first; // 1
last; // 3
length; // 3

将下标转为中文零一二三...

日常可能有的列表我们需要将对应的012345转为中文的一、二、三、四、五...,在老的项目看到还有通过自己手动定义很多行这样的写法,于是写了一个这样的方法转换

export function transfromNumber(number) {
  const  INDEX_MAP = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
  if (!number) return
  if (number === 10) return INDEX_MAP[number]
  return [...number.toString()].reduce( (pre, cur) => pre  + INDEX_MAP[cur] , '')
}

判断整数的不同方法

/* 1.任何整数都会被1整除,即余数是0。利用这个规则来判断是否是整数。但是对字符串不准确 */
function isInteger(obj) {
 return obj%1 === 0
}

/* 1. 添加一个是数字的判断 */
function isInteger(obj) {
 return typeof obj === 'number' && obj%1 === 0
}

/* 2. 使用Math.round、Math.ceil、Math.floor判断 整数取整后还是等于自己。利用这个特性来判断是否是整数*/
function isInteger(obj) {
 return Math.floor(obj) === obj
}

/* 3. 通过parseInt判断 某些场景不准确 */
function isInteger(obj) {
 return parseInt(obj, 10) === obj
}

/* 4. 通过位运算符*/
function isInteger(obj) {
 return (obj | 0) === obj
}

/* 5.ES6提供了Number.isInteger */

通过css检测系统的主题色从而全局修改样式