首页 JavaScript正文

JS一些特殊的使用

景先 JavaScript 2020-01-11 275 0

生成随机字符串

Math.random().toString(36).substring(2);

获取本地时间

new Date().toLocaleString().slice(10,19))

数组去重

var arr = [3, 9, 4, 3, 6, 0, 9];
//1
var newArr = arr.reduce((prev, cur) => {
  !prev.includes(cur) && prev.push(cur);
  return prev;
}, []);
//2
[...new Set(arr)]

数组合并

var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e'];

newArr = [...arr1,...arr2,...arr3]

对象合并

var o1 = {a:1,b:2}
var o2 = {b:3,c:4}

newObj = {...o1,...o2}

位运算取整

Math.floor(4.9) === 4 //true
~~4.9 === 4 //true 运行速度更快哟

表单验证重复使用

function validate(values) {
 if (!values.first) return false;
 if (!values.last) return false;
 return true;
}

console.log(validate({ first: 'edison', last: 'yuan' }))

const schema = {
 first: {
  required: true
 },
 last: {
  required: true
 }
}
const validate = (schema, values) => {
 for (field in schema) {
  if (schema[field].required) {
   if (!values[field]) {
    return false;
   }
  }
 }
 return true;
}

console.log(validate(schema, { first: 'edison' }))
console.log(validate(schema, { first: 'edison', last: 'yuan' }))

url相关操作(URLSearchParams)


const params = new URLSearchParams(location.search)
// 获取浏览器地址参数
params.get(key)
// 添加新参数
params.append(name,value)

相关地址

金额千分位划分

const AllMoney = (value) => {
    const regExp = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g;
    const money= (value + '').replace(regExp, '$1,');
    return money;
  };

获取时间戳

const timestamp = +new Date('2020-02-02')  // timestamp => 1580601600000

获取数组交集

const intersection = (list, ...args) => list.filter(item => args.every(list => list.includes(item)))

console.log(intersection([2, 1], [2, 3])) // [2]
console.log(intersection([1, 2], [3, 4])) // []

判断是否是移动端

const isMobile = () => 'ontouchstart' in window

禁止复制粘贴

const html = document.querySelector('html')
html.oncopy = () => false
html.onpaste = () => false

input只能输入中文

const input = document.querySelector('input[type="text"]')
const clearText = target => {
    const {
        value
    } = target
    target.value = value.replace(/[^\u4e00-\u9fa5]/g, '')
}
input.onfocus = ({target}) => {
    clearText(target)
}
input.onkeyup = ({target}) => {
    clearText(target)
}
input.onblur = ({target}) => {
    clearText(target)
}
input.oninput = ({target}) => {
    clearText(target)
}

去除字符串中html代码

const removeHTML = (str = '') => str.replace(/<[\/\!]*[^<>]*>/ig, '')
console.log(removeHTML('<h1>哈哈哈哈<呵呵呵</h1>')) // 哈哈哈哈<呵呵呵

数组拍平

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);

获取对象中的值存入数组

const cities = [
    { name: 'Paris', visited: 'no' },
    { name: 'Lyon', visited: 'no' },
    { name: 'Marseille', visited: 'yes' },
    { name: 'Rome', visited: 'yes' },
    { 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);
console.log(cityNames);

对象动态赋值

const dynamic = 'email';
let user = {
    name: 'John',
    [dynamic]: 'john@doe.com'
}
console.log(user); // outputs { name: "John", email: "john@doe.com" }
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

评论