5

1、解构小技巧

平常我们需要用到一个嵌套多层的对象中某些属性,会将其解构出来使用

let obj = {
  part1: {
    name: '零一',
    age: 23
  }
}

// 解构
const { part1: { name, age } } = obj
// 使用
console.log(name, age)  // 零一  23

这种情况下,你把 name 和 age 从 part1 里解构出来了以后,你就无法使用变量 obj 中的 part1 属性了,如:

// .... 省略

const { part1: { name, age } } = obj
console.log(part1)   // Uncaught ReferenceError: part1 is not defined
其实你可以多次解构,如:

// .... 省略

const { part1: { name, age }, part1 } = obj
console.log(part1)   // {name: "零一", age: 23}

2、一行代码生成随机字符串

const str = Math.random().toString(36).substr(2, 10);
console.log(str);   // 'w5jetivt7e'

先是 Math.random() 生成 [0, 1) 的数,也就是 0.123312、0.982931之类的,然后调用 number 的 toString方法将其转换成36进制的,按照MDN的说法,36进制的转换应该是包含了字母 a~z 和 数字0~9的,因为这样生成的是 0.89kjna21sa 类似这样的,所以要截取一下小数部分,即从索引 2 开始截取10个字符就是我们想要的随机字符串了

3、合并数据

const a = [1,2,3];
const b = [1,5,6];
const c = a.concat(b);//[1,2,3,1,5,6]

const obj1 = {
  a:1,
}
const obj1 = {
  b:1,
}
const obj = Object.assgin({}, obj1, obj2);//{a:1,b:1}

改进

const a = [1,2,3];
const b = [1,5,6];
const c = [...new Set([...a,...b])];//[1,2,3,5,6]

const obj1 = {
  a:1,
}
const obj2 = {
  b:1,
}
const obj = {...obj1,...obj2};//{a:1,b:1}

4、拼接字符串

const name = '小明';
const score = 59;
let result = '';
if(score > 60){
  result = `${name}的考试成绩及格`;
}else{
  result = `${name}的考试成绩不及格`;
}

改进

const name = '小明';
const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;

5、列表搜索

const a = [1,2,3,4,5];
const result = a.filter(
  item =>{
    return item === 3
  }
)

改进

const a = [1,2,3,4,5];
const result = a.find(
  item =>{
    return item === 3
  }
)

6、输入框非空的判断

if(value !== null && value !== undefined && value !== ''){
    //...
}

改进

if(value??'' !== ''){
  //...
}

7、时间戳转时分秒

// 时间转换
function timestampToTime(timestamp) {
  var date = new Date(parseInt(timestamp));//时间戳为10位需*1000,时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() + ' ';
  var h = (date.getHours() >= 10 ? date.getHours() : '0' + date.getHours()) + ':';
  var m = (date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes()) + ':';
  var s = (date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds());
  return Y + M + D + h + m + s;
}

8、文字复制功能

html:
<div class="detail">
    <span class="publicKey text-copy" title="测试">测试</span>
    <a class="copy">复制</a>
</div>

js:
 //封装公共方法:
 copyClick(content) {
    var _input = document.createElement('input'); // 直接构建input
    _input.value = content; // 设置内容
    document.body.appendChild(_input); // 添加临时实例
    _input.select(); // 选择实例内容
    document.execCommand('Copy'); // 执行复制
    document.body.removeChild(_input); // 删除临时实例
 }

  //方法调用
  $('.detail').on('click', '.copy', function (data) {
      copyClick(this.previousSibling.previousSibling.innerHTML);
  });

9、筛选单个数组重复值

arrRepeat: function (arr) {
    var hash = [],
        unhash = [];
    for (let i = 0; i < arr.length; i++) {
        if (unhash.indexOf(arr[i]) == -1) {
            unhash.push(arr[i]);
        } else {
            hash.push(arr[i]);
        }
    }
    return hash;
}

arrRepeat([1, 2, 3, 5, 3, 2, 56]);  // 2,3

10、使用 Async/Await 简化异步代码

Async/await 是一种简化 JavaScript 中异步代码处理的方法

async function getData() {
  const response = await fetch("https://xxx/xxx/xx");
  const data = await response.json();
  console.log(data);
}
getData();

11、将三元运算符用于条件逻辑

let x = 5;
let result = x > 0 ? "positive" : "negative";
console.log(result); // positive

也可以嵌套用于更复杂的条件

let age = 30;
let result = age < 18 ? "minor" : age >= 18 && age < 60 ? "adult" : "senior";
console.log(result); // adult

12、修改后端返回的json树形数据的字段名

 data: [
        {
          title: "江西",
          id: 1,
          children: [
            {
              title: "南昌",
              id: 1000,
              children: [
                {
                  title: "青山湖区",
                  id: 10001
                },
                {
                  title: "高新区",
                  id: 10002
                }
              ]
            },
            {
              title: "九江",
              id: 1001
            },
            {
              title: "赣州",
              id: 1002
            }
          ]
        }
]

// 把title这个字段名改为name

this.data = JSON.parse(JSON.stringify(this.data).replace(/"title"/g,'"name"'))

后续慢慢迭代》》


墨城
1.7k 声望2.1k 粉丝

« 上一篇
js截取