教你几招前端中的高级操作,你知道几种?

一、类型装换

1.快速转Number

var a = '1'

console.log(typeof a)
console.log(typeof Number(a)) // 普通写法
console.log(typeof parseInt()a) // 普通写法
console.log(typeof +a) // 高端写法

2.快速转 Boolean

var a = 0

console.log(typeof a)
console.log(typeof Boolean(a)) // 普通写法
console.log(typeof !!a) // 高端写法

小提示:
在js中==会把比较的二者进行类型转换,其中数字1为true、0、null、NAN、空字符串均为false。也就是说 0 == falsenull==false等等结果都为正确(true)的。而在===中,也可以在说严格模式下,这些都是不成立的,例如: 0===false结果为错误(false)的。

3.混写

先转为 Number 再转为 Boolean

var a = '0'

console.log(!!a) // 字符串数字直接转换得到 true,不符合预期
console.log(!!+a) // 先转为 Number 再转为 Boolean,符合预期。结果为false。

二、连续解构

1.最基本的解构

在对象中提取某个字段

const user = {
  id: 123,
  name: 'hehe'
};
const {name} = user;
console.log(name); //prints: hehe

2.解构嵌套对象

有时我们会遇到嵌套对象,如果我们了解未足够多时,会写出这种解构:

const user = {
  id: 123,
  name: 'hehe',
  education: {
    degree: 'Main'
  }
};

// 假设我们要提取degree
const {education} = user;
const {degree} = education;

当然这种写法是比较麻烦的,一层层的剥开,明显繁琐。其实我们可以连续解构一步到位的:

const user = {
  id: 123,
  name: 'hehe',
  education: {
    degree: 'Main'
  }
};
const {education: {degree}} = user;
console.log(degree); //输出结果为 Main

这种写法我通常会在element组件库中经常用到,比如在表格中:
通常写法:

  <el-table-column label="作者" prop="author" align="center" width="100px">
        <template slot-scope="scope">
          <span v-html="scope.row.authorWrapper" />
        </template>
  </el-table-column>

改进后的写法

  <el-table-column label="作者" prop="author" align="center" width="100px">
        <template slot-scope="{row:{authorWrapper}}">
          <span v-html="authorWrapper" />
        </template>
  </el-table-column>

这样是不是又简洁方便了许多呢?

当然,我们也会遇到另外一种情况:

从数组第一个对象元素中提取某个属性,比如:err 对象中包含一个 errors 数组,errors 数组每一个对象都包含一个 msg 属性

err = {
  errors: [
    {
      msg: 'this is a message'
    }
  ]
}

普通写法:

msg=err.errors[0].msg

连续解构写法:

const [{ msg }] = err.errors

如果您也正在学习前端的路上,记得关注该博主,学习更多关于前端的知识~

博主主页 Poetic Code

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值