javaScript常用操作技巧

javaScript常用操作技巧
获取最大值最小值

let arr = [15, 80, -9, 90, -99]

const max = Math.max.apply(Math, arr) 
const min = Math.min.apply(Math, arr)

const max = Math.max(...arr)
const min = Math.min(...arr)

数组去重

let arr = [1,1,2,4,53,232,32,23]
const tmp = [...new Set(arr)]

数组截取

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
// splice
arr.splice(0,4)
// length
arr.length = 4
// slice 运行更快,性能更好
arr.splice(0,4)

// 数组获取最后一项的值
// length
arr[arr.length-1]
// slice 取值为正值时从数组的开始处截取数组的项如果取值为负整数时可以从数组末属开始获取数组项
array.slice(-1)

清空数组

arr.length = 0
arr = []

数组排序(按字母排序)

var arr = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class']

const filterArr = arr.filter((v, i) => arr.lastIndexOf(v) === i) .sort((a, b) => a < b ? -1 : 1);

数组/对象合并

数组合并
const arr1 = [1,2,3]
const arr2 = [4,5,6]

const mergingArr = [...arr1,...arr2] // 等价arr1.concat(arr2)

对象合并
const obj1 = {
    name:"张三",
    age:18
}

const obj2 = {
    name:"李四",
    url:"www.xxx.com"
}

// 合并之后的对象会将之前已存在的属性值覆盖,不存在的新增
const mergingObj = {...obj1, ...obj2}

判断对象的数据类型

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target) 
const isArray = isType('Array')([1, 2, 3])

判断对象中是否包含

var obj = {
	name:"蔚蓝"
}
obj.hasOwnProperty('name') // true
obj.hasOwnProperty('age')  // false

使用in或者使用hasOwnProperty都可以,问题是两者检查属性的深度不同,换言之hasOwnProperty只在本身有此属性时返回true
in操作符不区分属性来自于本身或继承自原型链

数值转化字符串

// 使用运算符+后紧跟一组空的引号''快速地将数字或布尔值转为字符
var num = 100;
num+"";

字符串转化数值

// 使用运算符+加到字符串之前,可以将字符串转化为数值类型
var str = "100";	
+num;
console.log(+true)	 // 1
console.log(+false)  // 0 

浮点数转化整数(位运算符)

Math.floor()	// 向下取值
Math.ceil()		// 向上取值
Math.round()	// 四舍五入
num.toFixed(2)	// 保留两位小数
console.log(25.99 | 0)	 // 25 等同于Math.floor(25.99)
console.log(-25.99 | 0)	 // -25 
愿以往所学皆有所获
原文地址:https://www.cnblogs.com/Azune/p/14267323.html