前端常用js用法

814 阅读2分钟

类型转换


快速转 Number

var a = '1'
console.log(typeof a)    // string
console.log(typeof Number(a)) // 普通写法 number  a: 1
console.log(typeof +a) // 高端写法 number  a: 1

快速转 Boolean

在js中,!取反操作可将变量转换成boolean类型,null、undefined和空字符串取反都为true,其余都为false。而!!

var a = 0
console.log(Boolean(a)) // false
console.log(!a)    // true
console.log(!!a) // false    // 常用于获得Boolean的返回值

常用的场景为判断变量a不为nullundefined空字符串,也就是当a有内容

// 冗杂
if(a!=null&&typeof(a)!=undefined&&a!=''){
    // a有内容才执行的代码
}
// 简洁
if(!!a) {
    // a有内容才执行的代码
}

混写

先转为 Number 再转为 Boolean

var a = '0'console.log(!!a) // 直接转将得到 true,不符合预期
console.log(!!+a) // 先转为 Number 再转为 Boolean,符合预期

js 和 css 两用样式


template 中需要动态定义样式,通常做法:

<template>
  <div :style="{ color: textColor }">Text</div>
</template>
​
<script>
export default {
  data() {
    return {
      textColor: '#ff5000'
    }
  }
}
</script>

高端做法:

  • 定义 scss 文件
$menuActiveText: #409EFF;
​
:export {
  menuActiveText: $menuActiveText;
}
  • 在 js 中引用:

    • 使用 import 引用 scss 文件
    • 定义 computed 将 styles 对象变成响应式对象
    • 在 template 中使用 styles 对象
<template>
  <div :style="{ color: styles.menuActiveText }">Text</div>
</template>

<script>
import styles from '@/styles/variables.scss'
export default {
  computed: {
    styles() {
      return styles
    }
  }
}
</script>

数组解构

按变量位置解构

let [a, b, c] = [1, 2, 3]
// a:1  b:2  c:3

上面这段代码表示,可以从数组对应位置提取值对变量赋值

let [x] = ["first", "second", "third"]    // x: first
let [, x] = ["first", "second", "third"]    // x: second
let [ , , x] = ["first", "second", "third"]    // x: third

扩展运算符

let arr = [1,2,3]
console.log(...a)    // 1 2 3

对象解构


对象中的属性是无序的,解构的变量必须与属性同名。如果变量名在属性中不存在,解构失败,值为undefined。

let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
console.log(bar, foo)    // bbb aaa

let { a, b } = { foo: 'aaa', bar: 'bbb' };
console.log(a,b)    // undefined undefined

如果一定要将解构的属性赋值给不同名的变量,必须写成下面这种形式

let { foo: myFoo } = { foo: 'aaa', bar: 'bbb' };
// myFoo: aaa
// foo: foo is not defined

image.png

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

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

快速提取msg的方法为:

const [{ msg }] = err.errors

如果不用解构的写法为:

const msg = err.errors[0].msg

快速提取函数的多个返回值

function getUserInfo(uid) {
    // ...
 
    return {
        status: true,
        data: {
            name: '小红'
        },
        msg: '请求成功'
    };
};
 
const { status, data, msg: message } = getUserInfo(123);

练习

1. 根据Dog API返回的结果res获取图片idurl

image.png

// 获取url
let [{ url }] = res
console.log(url)    // https://cdn2.thedogapi.com/images/Z8LiOtceX.jpg
// 获取id
let [{ breeds: [{id}] }] = res
console.log(id)    // 3

2. 合并数组

const left = [1,2,3,4]
const mid = 5
const right = [6,7,8,9]

将上面两个数组leftright和中间数mid合并为一个数组

console.log([...left, mid, ...right])    // [1, 2, 3, 4, 5, 6, 7, 8, 9]