推荐10个前端常用开发技巧

382 阅读2分钟

一、数组转字符串

方式1:

['a', 'b', 'c'].join(',') // 'a,b,c'

方式2:

['a', 'b', 'c'].toString() // 'a,b,c'

二、逗号参数解构赋值

function foo(...args) {
    const [a,,c] = args
    console.log(a, c) // 1 3
}
foo(1, 2, 3)

三、删除所有localStorage

const localStorageValues = localStorage.valueOf();
for(let k in localStorageValues) {
    localStorage.removeItem(k);
}

四、一维数组分段转二维数组

const data = [
    {"id":1,"name":"系统集成"},
    {"id":2,"name":"公告"},
    {"id":3,"name":"信息系统"},
    {"id":4,"name":"考试必看"},
    {"id":5,"name":"心得笔记"},
    {"id":6,"name":"考试心得"}
]
const cData = []

for(let i in data) {
    if(i === 0) {
        cData[0] = [data[i]]
    } else {
        if(i % 4 === 0) { // 4可以改为任意分隔数
            cData[cData.length] = [data[i]]
        } else {
            cData[cData.length-1].push(data[i])
        }
    }
}

console.log(cData)
// [
//     [{"id":1,"name":"系统集成"},{"id":2,"name":"公告"},{"id":3,"name":"信息系统"},{"id":4,"name":"考试必看"}],
//     [{"id":5,"name":"心得笔记"},{"id":6,"name":"考试心得"}
// ]

五、快速合并数组和对象

合并数组:

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}

六、网站屏蔽开发者工具

let num = 0;
const devtools = new Date();
devtools.toString = function () {
  num++;
  if (num > 1) {
    console.log('Console is opened');
    window.location.href = "http://www.baidu.com";
  }
};
console.log(devtools);

七、刷新页面

  • history.go(0)
  • location.reload()
  • location=location
  • location.assign(location)
  • document.execCommand('Refresh')
  • window.navigate(location)
  • location.replace(location)
  • document.URL=location.href

八、递增填充数组

方式1:

[...Array(24)].map(function(v, i) { return i; }) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

方式2:

Array.from({length: 24}, function(v, i) { return i; }) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

方式3:

Array(24).fill(null).map(function(v,i) { return i; }) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

九、字符串重复

方式1:通过添加原型方法

String.prototype.repeat = function(n) {
    var str = '';
    for(var i=0; i<n; i++) {
        str += this;
    }
    return str;
}
'abc'.repeat(3); // abcabcabc

方式2:通过ES6 repeat方法

'abc'.repeat(3); // abcabcabc

方式3:通过replace

'abc'.replace(/(abc)/, '$1$1$1')

十、巧用bind

var $ = document.querySelector.bind(document);
$('.box').textContent = 'hello world ~';

更多前端知识,请关注小程序,不定期有惊喜!

image.png