js小技巧

数组去重

// 方法一
const array = [1, 2, 2, 3, 6, 6, 5, 1]; let arr1 = [...new Set(array)]
// 方法二
let arr2 = Array.from(new Set(array))
//方法三
let arr3 = array.filter((arr, index) => array.indexOf(arr) === index) //

过滤掉数组中的false

const array = [0, 1, '0', '1', '测试',  undefined, true, false, null, NaN,'undefined', 'null', 'NaN']; 
array.map(item => { return item }).filter(Boolean)

展开数组

const arr = [1, [2, 5], 3, [false, '1', 2, 3, '哈哈']];
const flatArray = [].concat(...arr)

获取数组最大最小值

const numbers = [115, 50, -92, 70, 199, 30, -2];
// 方法一 const maxInNumbers
= Math.max.apply(Math, numbers); const minInNumbers = Math.min.apply(Math, numbers);
// 方法二
const maxInNumbers = Math.max(...numbers);
const minInNumbers = Math.min(...numbers);

合并对象

const obj1 = { name: '小明', address: 'China' };
const obj2 = { name: 'leo', age: 24 };
const mergingObj = {...obj1, ...obj2}

合并数组对象

const array = [ { name: 'jack', age: '22' }, { name: 'leo', age: '21' } ];
const result = array.reduce((accumulator, item) => { return { ...accumulator, [item.name]: item.age } }, {})

根据条件添加对象属性

const getUser = (emailIncluded) => { return { name: 'leo', age: '21', ...emailIncluded && {email: 'leo@163.com'} } };
const user = getUser(true)

结构原始数据

const obj = { name: 'leo', age: '21', email: 'leo@163.com', address: 'China', wight: 65 };
let user = {}, userDetails = {} ({name: user.name, email: user.email, ...userDetails} = obj)

动态更改对象key

const dynamicKey = 'email';
let obj = { name: 'leo', [dynamicKey]: 'leo@163.com' }

判断数据类型

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

判断对象是否含有某个属性

var obj = { name: 'leo' }; 
obj.hasOwnProperty('name'); // > true
'name' in obj; // > true
obj.hasOwnProperty('valueOf'); // > false, valueOf 继承自原型链 
'valueOf' in obj; // > true

 创造一个纯对象,不继承Object任何属性和方法

const pureObject = Object.create(null);

后续更新...

 

posted @ 2019-06-20 16:12  张石磊博客  阅读(306)  评论(0)    收藏  举报