教你幾招前端中的高級操作,你知道幾種?

一、類型裝換

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章