自学内容网 自学内容网

【ES6】使用记录

Symbol

const sym = Symbol('Mo_qyue');
console.log(sym.description)  //'Mo_qyue'
  • 作为属性名Symbol
let mySymbol = Symbol()
let a = {}
a[mySymbol] = 'hello';
console.log(a[mySymbol]) //hello

let b={[mySymbol]:'hello'}
console.log(b[mySymbol]) //hello

let c=Object.defineProperty({},mySymbol,{value:'hello'})
console.log(c[mySymbol])//hello
  • 注意,Symbol值作为对象属性名时,不能用点运算符
const mySymbol = Symbol()
const a = {}
a.mySymbol = 'hello'
console.log(a['mySymbol']) //"hello"
a[mySymbol]//这个是访问不到的
const obj = {}
let a = Symbol('a')
let b = Symbol('b')
obj[a] = 'hello'
obj[b] = 'World'
let cArr = Reflect.ownKeys(obj)
for (let item of cArr) {
  console.log(obj[item])
  //hello
  // World
}
  • Symbol.for()

Symbol.for()与Symbol() 都会生成新的Symbol,他们的区别是,前者会被登记在全局进行搜索,后者不会


let s1 = Symbol('foo')
let s2 = Symbol('foo')
console.log(s1 === s2)//false
let s3 = Symbol.for('foo')
let s4 = Symbol.for('foo')
console.log(s3 === s4)//true
  • Symbol.iterator
    对象的Symbol.iterator属性,指向该对象的默认遍历器的方法
const a = {}
a[Symbol.iterator] = function* () {
  yield 1;
  yield 2;
  yield 3
};
console.log([...a])

判断非空isEmpty

const isEmpty=val=>val===null||!(Object.keys(val)||val).length

判断一个字符串是否有重复的字符

//采用桶排序的思想
const isData = str => {
  let flag = Array.from({ length: 128 }, v => 0)
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (flag[c] > 0) {
      return false
    } else {
      flag[c]++
    }
  }
  return true
}
console.log(isData('abc'))

判断两个字符集是否相同

const equls = (s1, s2) => {
  const map = new Map();
  for (let i = 0; i < s1.length; i++) {
    if (map.get(s1[i]) == null) {
      map.set(s1[i], 1)
    }
  }
  for (let i = 0; i < s2.length; i++) {
    if (map.get(s2[i]) === null) {
      return false
    }
  }
  return true
}

判断是否是旋转词


const joint = (str, s1) => {
  let a = ''
  let b = [];
  for (let i = 0; i < str.length; i++) {
    if (i == 0) {
      a = str.slice(i)
    } else {
      a = str.slice(i) + str.slice(0, i)
    }
    b.push(a)
  }
  return b.indexOf(s1) > -1 ? true : false
}

String


String.prototype.charAt(index)     0<=index<=length-1   返回特定位置的字符

String.prototype.charCodeAt(index)                      返回给定的字符的Unicode值

String.prototype.concat()                               连接两个字符串文本,返回新的字符串

String.prototype.includes()       判断字符串是否包含                      

endsWith()  判断当前字符串是否是以另外一个给定的子字符串'结尾'  Boolean
startsWith()                                          '开头' Boolean

String.localeCompare()       'abcsbda'.split('').sort((a, b) => a.localeCompare(b))

String.prototype.padEnd()       两个参数,第一个数字符串的最大长度,第一个参数是添加的字符串,长度不能超过max.length

repeat()    重复的次数
replace()    替换
slice()  

比较

类型运算规则
两个值类型进行比较直接比较数据在序列中的大小
值类型与引用类型比较将引用类型的数据转换为与值类型数据相同的数据
两个引用类型比较无意义,总是返回false
console.log('b' > 'a')  //true

对象与数组互转

// 状态码说明: 100->对账成功、101->对账中、102->审核中、103->对账失败、104->取消对账
// 规定有如下样式映射表: 
const style2StatusMap = {
  success: [100],
  warning: [101,102],
  danger: [103,104]
}
//结果
const status2styleMap = {
  100: 'success',
  101: 'warning',
  102: 'warning',
  103: 'danger',
  104: 'danger'
}

const status = obj =>
  Object.entries(obj)
    .reduce((acc, val, i, array) => {
      val[1].map(item => {
        acc[item] = array[i][0]
      })
      return acc
    }, {})

Set

  • 由于Set结构没有键名,只有键值所有keys方法和values方法的行为完全一致
let a=new Set([1,2,3,4])
             //a.keys()    a.values() 或者直接用of遍历
for (let item of a) {
    console.log(item)
}
/*
 * 1,2,3,4
 * */
  • forEach()
let a = new Set([1, 2, 3, 4])
let b = [];
a.forEach(v=>b.push(v))
console.log(b)
  • 数组的map和filter方法也可以间接用于Set
let set =new Set([1,2,3])
let set1=new Set([...set].map(v=>v*2))
console.log(set1)
//Set { 2, 4, 6 }
let set2=new Set([...set].filter(v=>v%2==0))
console.log(set2)
// Set { 2 }
  • 使用Array.from()
let set = new Set([1, 2, 3, 4])
let set1 = Array.from(set, val => val * 2)
console.log(set1)
//[ 2, 4, 6, 8 ]

判断undefined

const isUndefined = value => value == void 0
let a;
console.log(isUndefined(a)) //true

合并对象


const isObject = value => toString(value) === '[object Object]'

const merage = (a, b) => {
  for (let item in b) {
    if (isObject(b[item])) {
      a[item]=merage(a[item],b[item])
    }else{
      a[item]=b[item]
    }
  }
  return a
}

去重value

const uniqueBy = (arr, fn) => {
  return arr.filter((val, index, array) => {
    return array.findIndex(item =>
        typeof (fn) == 'function' ? fn.call(this, item) == fn.call(this, val)
          : val[fn] == item[fn])
      == index
  })
}

递归逆序

const fun = num => {
  let num1=num/10
  let num2=num%10
  if (!Math.floor(num1)) {
    return num
  }
  if (Math.floor(num1)) {
    return `${num2}`+fun(Math.floor(num1))
  }
}
console.log(fun('12345'))
//不用递归,不用api
const fun = num => {
  let end=num.length-1
  let sum=''
  while (end>=0) {
    sum+=num[end]
    end--
  }
  return sum
}
console.log(fun('12345'))

禁止右键,选择,复制

// 鼠标右键事件   选择             复制
['contextmenu', 'selectstart', 'copy'].forEach(function (ev) {
    document.addEventListener(ev, function (event) {
        return event.preventDefault()
    })
})
//event.preventDefault()  阻止默认的点击事件执行

递归

//阶乘
const fact = n => {
    if (n == 1) {
        return n
    }
    return fact(n - 1) * n
}
 console.log(fact(5))

//最大公约数
const gcd = (a, b) => {
    if (b == 0) return a
    return gcd(b, a % b)
}
console.log(gcd(5, 10))
// 走楼梯(一个台阶总共有n级台阶,如果一次可以跳1,2,
//问有多少种可能
const solve=n=>{
    if(n==1)  return 1
    if(n==2)  return 2
    return solve(n - 1) + solve(n - 2)
}
console.log(solve(2))

//归并排序
const mergeSort = array => {
    if (array.length < 2) return array
    let mid = Math.floor(array.length / 2)
    let left = array.slice(0, mid)
    let right = array.slice(mid)
    return merge(mergeSort(left), mergeSort(right))
}
const merge = (left, right) => {
    let result = []
    while (left.length > 0 && right.length > 0) {
        if (left[0] < right[0]) {
            result.push(left[0])
        } else {
            result.push(right[0])
        }
    }
    return result.concat(left).concat(right)
}

数字前面加密


const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask);

mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, -4, '$'); // '$$$$567890'

字符串倒序

const reverseString = str => [...str].reverse().join('');

reverseString('foobar'); // 'raboof'

字符串升序

localeCompare 可以用来判断升序还是降序

const sortCharactersInString = str =>
[...str].sort((a, b) => a.localeCompare(b)).join('');

Array.from

const cities = [
    { name: 'Milan', visited: 'no' },
    { name: 'Palermo', visited: 'yes' },
    { name: 'Genoa', visited: 'yes' },
    { name: 'Berlin', visited: 'no' },
    { name: 'Hamburg', visited: 'yes' },
    { name: 'New York', visited: 'yes' }
];

const cityNames = Array.from(cities, ({ name}) => name);
解构
cities.map(({name}) => name);

//给数组分组
const chunk=(arr,size)=>{
   return  Array.from({length:Math.ceil(arr.length/size)},(v,i)=>arr.slice(i*size,size*(i+1)))
};

console.log(chunk([1, 2, 3, 4, 45], 2)); //[ [ 1, 2 ], [ 3, 4 ], [ 45 ] ]

去重

//对象的属性是唯一的
let tempList = [12, 3, 43, 5, 56, 34, 2, 1, 3, 4, 5];
Object.keys(tempList.reduce((acc, val) => (acc[val] = 0, acc), {})).map(Number);

原文地址:https://blog.csdn.net/Mozifei73/article/details/137788983

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!