Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

usefull-code-snippets #12

Open
itstrive opened this issue Jan 11, 2019 · 1 comment
Open

usefull-code-snippets #12

itstrive opened this issue Jan 11, 2019 · 1 comment
Labels
article small article

Comments

@itstrive
Copy link
Owner

itstrive commented Jan 11, 2019

获取一个地址的参数

const getURLParameters = (url=location.href) =>
    (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
	(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
	{}
    );

console.log(getURLParameters()); //不传参数默认获取当前地址
console.log(getURLParameters('https://www.baidu.com/s?wd=s&rsv_spt=1&rsv_sug4=4')); //{wd:'s', rsv_spt:'1', rsv_sug4:'4'}

httpGet

const httpGet = (url, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send();
};

httpPost

const httpPost = (url, data, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send(data);
};

isBrowser

const isBrowser = () => ![typeof window, typeof document].includes('undefined');

随机一个16进制的颜色

const randomHexColorCode = () => {
  let n = (Math.random() * 0xfffff * 1000000).toString(16);
  return '#' + n.slice(0, 6);
};

转货币

const toCurrency = (n, curr, LanguageFormat = undefined) =>
  Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);

console.log(toCurrency(123656.789, 'CNY')); //¥123,656.79
console.log(toCurrency(123656.789, 'USD','en-us')); //$123,656.79

具体参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

@itstrive itstrive added the article small article label Jan 11, 2019
@itstrive
Copy link
Owner Author

简单实现一个sleep

用 promise + async await实现

var sleep = function(time, i){
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            resolve(i);
        },time)
    })
}

var run= async function(){
    for(var i=0; i<10; i++){
        var res = await sleep(2000,i);
        console.log(res);
    }
};

run();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
article small article
Projects
None yet
Development

No branches or pull requests

1 participant