飞道的博客

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

399人阅读  评论(0)

一、类型装换

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


转载:https://blog.csdn.net/weixin_44253336/article/details/106470980
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场