2

前端小知识点

 2 years ago
source link: https://segmentfault.com/a/1190000041035595
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

前端小知识点

发布于 11 月 29 日

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;
}

有更好的方式可以补充


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK