1:数组求和使用reduce
let nums = [1,22,31,4,56]let sum = nums.reduce((prev, cur) => prev + cur, 0)
2:数组去重
let arr = [1,1,2,434,2,1]console.log([...new Set(arr)]) // 1 2 434
3:数组里的值是否满足一个要求
let list = [1,2,2,2,2,2]let res = list.some(item => item > 1)console.log(res) // true
4:数组里的值是否都满足要求
let list = [1,2,2,2,2,2]let res = list.every(item => item > 1)console.log(res) // false
5:检测值是否为数组
let arr = []console.log(Array.isArray(arr)) // trueconsole.log(Object.prototype.toString.call(arr) == "[object Array]") // true
6:数组转换为对象
let person = ["蛙人", 24, "male"]let obj = {}person.forEach(item => (obj[item] = item))
7:使用Map使数组直接返回结果
let person = [10, 20, 30]function fn(item) {return item + 1}let res = person.map(fn)console.log(res) // [11, 21, 31]
8:是否为奇偶数
let num = val => val % 2 == 0;num(10) // ture 偶数num(1) // false 奇数
9:交换变量
let x = 10;let y = 20;[x, y] = [y, x];
10:生成随机id
Math.random().toString(36).substr(2)
11获取对象key键值
let person = {name: "蛙人", age: 24};console.log(Object.keys(person)) // ["name", "age"]
12获取对象value值
let person = {name: "蛙人", age: 24};console.log(Object.values(person)) // ["蛙人", 24]
13获取对象里指定的值(解构)
const person = {name: "蛙人", age: 24, sex: "male"};let { age, sex } = personconsole.log(age, sex) // 24 male
14合并对象
let person = {name: "蛙人", age: 24}let obj = Object.assign({}, person)console.log(obj) // {name: "蛙人", age: 24}
15模板字符串表达式
let name = "蛙人"console.log(`hello ${name}`)console.log(`<p>${name}</p>`)
16快速将字符串转换为数组。使用扩展运算符可以快速转换为数组。
let str = "abcdefg"console.log([...str]) // ["a", "b", "c", "d", "e", "f", "g"]
17使用三目运算判断值(抛弃if else。)
let status = 1;status = status == 1 ? "男" : "女"
18:反转字符串
const reverse = str => str.split('').reverse().join('');reverse('hello world');// 'dlrow olleh'
19:防抖节流
Js中防抖与节流
自动生成常用javascript代码工具:
JS常用代码生成器_js代码在线生成
js代码美化:
Javascript或HTML在线美化,格式化
知识巩固:
javascript面试题大全_Js基础面试题(附答案)
参考手册:
JavaScript核心参考列表