前端开发技巧记录

1.取数组最后一位

let arr=[1,2,3,4,5]
console.log(arr[arr.length-1]) //5
console.log(arr.at(-1)) // 5

2.用??代替||,判空
||运算符是左边是‘’ false 0 null undifined等,都会返回后侧的值。而??必须运算符左侧的值为null或undefined时,才会返回右侧的值。

0||1  //1
0??1   //0

3.链判断运算符?.直接在链式调用的时候判断,判断左侧的对象是否为null或undefined,如果是就不再往下运算,返回undefined,如果不是,则返回右侧的值

obj?.prop 对象属性
obj?.[expr] 对象属性
func?.(...args) 函数或对象方法的调用

4.当有输入框的添加type="password"时,阻止谷歌浏览器自动填充

//第一个输入框添加
autocomplete="off"
//密码框添加
autocomplete="new-password"

5.使用display:inline-block;会出现间隔,在其父级添加:font-size:0,同时添加

-webkit-text-size-adjust:none //取消谷歌浏览器的字体最小限制12px

6.文本溢出

//单行省略
.single{
    
    
	white-space:nowrap;
	overflow:hidden;
	text-overflow:ellipsis;
}
//多行省略
.ellipsis{
    
    
    letter-spacing: 0;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;  //4行
    overflow: hidden;
    text-overflow:ellipsis;
    work-break:break-all;

}

7.防止鼠标选中事件

onslectstart="return false" //目标元素上添加该事件

8.登录表单可以在 标签上添加 @submit.prevent,阻止默认提交表单行为

9.在浏览器中的一些骚操作(将以下代码粘贴到浏览器地址栏正常执行~)

浏览器直接运行JavaScript ,IE&Chrome回自动去掉代码开头的javascript:,Firefox虽然不会自动去掉,但是它也不支持地址栏运行JS代码

javascript:alert('hello word !');   

浏览器地址运行HTML代码

data:text/html,<h1>Hello, world!</h1>

浏览器也可以当作编辑器

data:text/html, <html contenteditable>  //浏览器地址栏执行
document.body.contentEditable='true';  //浏览器开发者模式控制台执行

10.过滤数组中的false、0、null、undefined等值

[1, 0, undefined, 6,  "", false].filter(Boolean);
//[1, 6]

11.includes取代多条件判断
if(a === undefined || a === 10 || a=== 15 || a === null) { //… }

if([undefined, 10, 15, null].includes(a)) {
    
     //… }

12.初始化数组

//一维数组  
const array = Array(6).fill(‘’); // [‘’, ‘’, ‘’, ‘’, ‘’, ‘’]
//二维数组
const matrix = Array(6).fill(0).map(() => Array(5).fill(0));

在这里插入图片描述

13.合并数组

const start = [1, 2] 
const end = [3,4,5]
start. concat(end); //[1,2,3,4,5]

但是在使用 concat() 方法时,如果要合并的数组很大,concat() 函数在创建单独的新数组时会消耗大量内存。这时候可以使用以下方法合并数组:

Array.prototype.push.apply(start, end)

14.数组元素转换为数字

array.map(Number)

15.检查对象是否为空

Object.keys({
    
    }).length  //0

16.把 NodeList / HTMLCollection 类数组转变为真正的 Array 添加原生数组方法

[...document.querySelectorAll('div')].map

17.删除数组重复项

const numbers = [1, 1, 20, 3, 3, 3, 9, 9];
const uniqueNumbers = [...new Set(numbers)]; //  [1, 20, 3, 9]

18.对象的深浅拷贝

let newObj=JSON.parse(JSON.stringfy(oldObj))  //深拷贝,但对象中不能包含 function 或 RegExp 
Object.assign(newObj,oldObj)  //对象仅有一级时为深拷贝,有二级属性即为浅拷贝
import cloneDeep from 'lodash/cloneDeep';
let newObj=cloneDeep(oldObj)   //深拷贝

19.数组对象查过滤出符合条件项
find 和 filter 都不改变原数组,但是只查出第一个符合条件的结果并直接返回一个对象,无返回undifined;filter返回全部结果的数组对象,无返回空数组

let obj=[{
    
    name:'李四',age:10},{
    
    name:'张三',age:15},{
    
    name:'李四',age:18}]
obj.find((el)=>(el.name =='李四'));   //{name:'李四',age:10}
obj.filter((el)=>(el.name =='李四'));   //[{name:'李四',age:10},{name:'李四',age:18}]

猜你喜欢

转载自blog.csdn.net/qq_45840993/article/details/127983861
今日推荐