查看原文
其他

JavaScript 开发者都应掌握的 8 种实用的编码技术

小懒 FED实验室 2024-02-12
关注下方公众号,获取更多热点资讯

相信坚持的力量!今天是坚持日更的第116天,点击关注、点赞、在看支持我


本文将分享 8 种实用的 JavaScript 编码技术,掌握后将大大提高你的工作效率。

1.对象深拷贝

在日常开发中,对象合并及复制场景很常见,通常的实现方式都是采用遍历的方式。是否有其他更遍历的方式?今天给大家介绍一个新的全局函数structuredClone()

1)兼容性:

structuredClone() 已经被所有现代浏览器所支持。

注意:Node.js 在 v17 版本及以上可用。

2)代码示例:

const Blog = {
  name'FED实验室',
  user: {
    name'小懒',
    sex'female',
    age'28'
  },
};
const cloned = structuredClone(Blog);
cloned.user.id = 'ifedlab';
cloned.user.company = 'Tencent';

// Output: 
// { name: 'FED实验室', user: { name: '小懒', sex: 'female', age: '28' } }
console.log(Blog);

// Output: 
// {
//   name: 'FED实验室',
//   user: {
//     name: '小懒',
//     sex: 'female',
//     age: '28',
//     id: 'ifedlab',
//     company: 'Tencent'
//   }
// }
console.log(cloned);

structuredClone() 不会产生滥用其他 API 的开销,并且比 JSON.parse() 更可靠,因此建议您将其作为创建深拷贝的默认方法。

2.生成随机颜色值

Web 开发中,常用的颜色类型有颜色名称(如:red)、rgba、十六进制颜色、hsla,下面是一个通用的随机生成颜色值的函数。

const generateRandomColor = (type) => {
  if(type === 'hex') {
    return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
  } else if (type === 'rgba') {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    const a = Math.random().toFixed(2);
    return `rgba(${[ r, g, b, a ].join(',')})`
  } else if (type === 'hsla') {
    return `hsla(${ Math.floor(Math.random() * 360) },100%,50%,1)`;
  }
  const defaultColors = ['red''orange''blue''yellow']
  return defaultColors[Math.floor(Math.random() * defaultColors.length)];
};

// Output: #48e0a5
console.log(generateRandomColor('hex'));

// Output: rgba(48,244,225,0.09)
console.log(generateRandomColor('rgba'));

// Output: hsla(69,100%,50%,1)
console.log(generateRandomColor('hsla'));

// Output: blue
console.log(generateRandomColor());

3.模拟 sleep 函数

JavaScript 原生不支持 sleep() 函数,下面通过 Promise 来实现 sleep 函数功能。

const sleep = (millisecond) => {
  return new Promise((resolve) => {
    const timer = setTimeout(() => {
      clearTimeout(timer);
      return resolve('success');
    }, millisecond);
  });
};

async function main() {
  const startTime = Date.now();
  const status = await sleep(2000);
  const cost = Date.now() - startTime;

  // Output: status: success, cost: 2005
  console.log(`status: ${status}, cost: ${cost}`);
}

main();

4.获取选中的文本

对于 Web 开发中,尤其英文不好的同学,在浏览器中阅读外网文章时,经常会使用划词翻译、高亮选中等功能,下面看看简单实现。

const getSelectedContent = () => window.getSelection().toString();

5.获取 Cookie

const getAllCookies = () {
  return document.cookie.split(';').reduce((result, cookie) => {
    const [key = '', value = ''] = cookie.split('=');
    result[key.trim()] = value.trim()
    return result;
  }, {});
};

const getCookie = (key) => {
  if(!key) return '';

  const cookies = getAllCookies();
  return cookies[key];
}

// Output: all cookies
console.log(getAllCookies());

// Output: F26F071EBC71A9FBD70875B35EDDC919
console.log(getCookie('BAIDUID'));

6.获取 URL 参数

获取 URL 参数应该是日常开发中比较常用的功能了。

1) 传统方式:

const parser = (url) => {
  const a = document.createElement('a');
  a.href = url || window.location.href;

  const search = a.search;

  return {
    href: a.href,
    host: a.host || location.host,
    port: ('0' === a.port || '' === a.port) ? port(a.protocol) : a.port,
    hash: a.hash,
    hostname: a.hostname || location.hostname,
    pathname: a.pathname.charAt(0) !== '/' ? `/${a.pathname}` : a.pathname,
    protocol: !a.protocol || ':' === a.protocol ? location.protocol : a.protocol,
    search,
    searchParams: parseQuery(search.slice(1)),
  };
};

const parseQuery = (querystring) => {
  const params = {};
  const qureylist = (querystring || '').split('&');
  for (const i = 0; i < qureylist.length; i++) {
    const item = qureylist[i];
    const [key = '', value = ''] = item.split('=');
    if (key) {
      try {
        value = value.replace(/[+]/g'%20');
        params[key] = decodeURIComponent(value);
      } catch (e) {
        params[key] = value;
      }
    }
  }
  return params;
};

// Output: 刘德华
console.log(parser().searchParams.query);

2) 新的方式:

const parser = (url) => {
  return new URL( url || window.location.href)
}
const parseQuery = (url) => {
  return parser(url).searchParams;
}

// Output: 刘德华
console.log(parseQuery().get('query'));

7.数组随机排序

const shuffle = (array) => array.sort(() => 0.5 - Math.random());

// Output: [ 0, 1, -4, 2, -1, 3 ]
console.log(shuffle([ 1-1230-4 ]));

8.复制内容到剪贴板

1)方式一:

const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text);

copyToClipboard('FED实验室')

2)方式二:

const copyToClipboard = (content) => {
  const textarea = document.createElement("textarea")
  
  textarea.value = content;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('Copy');
  textarea.remove();
};

copyToClipboard('FED实验室');

大家都在看

继续滑动看下一个

JavaScript 开发者都应掌握的 8 种实用的编码技术

小懒 FED实验室
向上滑动看下一个

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存