你值得拥有的前端优雅小技巧

2,453 阅读2分钟

一、JavaScript篇

(一)、取值

const obj = {
    a:1,
    b:2,
    c:3,
    d:4,
    e:5,
}

从obj对象中取值

一般写法:

const a = obj.a;
const b = obj.b;
const c = obj.c;
const d = obj.d;
const e = obj.e;
const f = obj.a + obj.d;
const g = obj.c + obj.e;

改进后的代码

const {a,b,c,d,e} = obj;
const f = a + d;
const g = c + e;

需要注意的是,解构的对象不能为undefined、null。否则会报错,所以要给被解构的对象一个默认值。

const {a,b,c,d,e} = obj || {};

(二)、深度解构

let obj = {
  name: "yyy",
  a: {
    b: 1
  }
}


const { a: { b } } = obj;
console.log(b); // 1

(三)、${} 的使用

在${}中可以放入任意的JavaScript表达式,比如,可以进行运算,以及引用对象的属性等。

const name = 'yyy';
const score = 59;
let result = '';
if(score > 60){
  result = `${name}的考试成绩及格`; 
}else{
  result = `${name}的考试成绩不及格`; 
}

改进后的代码

const name = 'yyy';
const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;

(四)、对象解构、变量重命名

  const data = { code: 200, msg: '哈哈哈哈' }
  const { code: code1, msg: msg1 } = data
  const { code: code2, msg: msg2 } = data
  console.log('code1,msg1===>', code1, msg1)
  console.log('code2,msg2===>', code2, msg2)

(五)、if中的多种条件判断

  if (a == 1 || a == 2 || a == 3 || a == 4) {
     //TODO
  }

改进后的代码

  const a = 1
  const b = [1, 2, 3, 4]
  if (b.includes(a)) {
    //TODO
  }

(六)、可选运算符 ?

const name = obj && obj.name;

改进后的代码:

const name = obj?.name;

(七)、有条件地向对象添加属性

const businessModel = 'sbc';
const param = {
  id: 1,
  name: "yyy",
  ...(businessModel=='o2o' && { businessModel: businessModel }),
};
console.log(param)

打印的结果:
 {
  id: 1,
  name: "yyy",
};

(八)、判断数组长度不为零

if (arr.length !== 0) {
    ...
}

改进后的代码

if (!!arr.length) {
    ...
}

(九)、 空值合并运算符 ??

空值合并运算符 ?? 用于判断左侧表达式的值是否是 null 或 undefined,如果是返回右侧的值。

  let data
  let newData
  if (data !== null && data !== undefined) {
    newData = data
  } else {
    newData = '嘻嘻嘻'
  }
  console.log('newData===>', newData)

改进后的代码

const newData = data ?? '嘻嘻嘻'
console.log('newData===>', newData)

(十)、使用 !! 操作符

!! 运算符可用于将表达式的结果快速转换为布尔值(true或false)

const a = 'Hello!';
console.log(!!a) // true

const b = '';
console.log(!!b); // false

(十一)、获取数组中位置最后的一个元素

const arr = [1,2,3,4]
// before
console.log(arr[arr.length-1])
// after
console.log(arr.at(-1))
//补充
console.log(arr.at(-1)) // 倒数第一个值
console.log(arr.at(-2)) // 倒数第二个值
console.log(arr.at(0)) // 正数第一个  
console.log(arr.at(1)) // 正数第二个

(十二)、 使用解构交换两个变量的值

let x = 'hello', y = 100;

// before
const temp = x;
x = y;
y = temp;

// after
[x, y] = [y, x];

二、CSS篇

(一)、 使用 :not() 来精简css代码

// 不使用:not()
.nav li {
  border-right: 1px solid #666;
}
.nav li:last-child {
  border-right: none;
}

// 使用:not()
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}

(二)、css强制换行

有些情况下,文字内容换行,但是数字和字母不会换行显示

比如:

image.png

审查元素查看内容可以知道,内容很长,都是1111111111

image.png

white-space:normal;
word-break:break-all;

也就是,不管是啥,都让内容强制换行

image.png