js常用技巧

  • 小数取整 

  1.234 | 0

  ~~1.234

  1.234 >> 0
  • 妙用隐式转换

1.字符串转number:
  +'123'

2.new Date转时间戳:
  +new Date()

3.数组/多维数组转为逗号分隔字符串(可用于多维数组转一维):
  ""+[1, 2 , 3, 3, [2, 3, 4]]
  • 解构

交换a,b的值:
  var a=1;
  var b=2;
  [a, b] = [b, a];
  • 扩展运算符:

取数组最大值/最小值:
  Math.max(...[1,2,3])
  Math.min(...[1,2,3])

生成时间:
  new Date(...[2018,6,4])

字符串转数组:
  method 1: 
  [...'string']
  
  method 2: 
  Array.from('string')

合并对象:
  let obj1 = {a:1, b:2};
  let obj2 = {b:3, c:4};

  {...obj1, ...obj2}

    等同于
  Object.assign(obj1, obj2)
  • 利用URL API获取url的query值

var url = new URL('http://localhost:8000/news?a=1&b=2&c=3');
var searchParams = url.searchParams;
for (let key of searchParams.keys()){
  console.log('====');
  console.log('key === ', key);
  console.log('value === ', searchParams.get(key))
}
  • 常用方法

数组元素为对象的去重:
  [...new Set(arr.map(v => JSON.stringify(v)))].map(v => JSON.parse(v))

数组求和:
  var arr = [1,2,3,4,5];
  
  method 1: 
  var sum = eval(arr.join('+'));
  
  method 2: 
  var sum = arr.reduce((prev,cur) => prev + cur);

你可能感兴趣的:(javascript)