都是為了混那10000礦石,文章內容摘抄自各大博主(太多了鏈接找不到,求輕打!!)
?.(可選操作符):移動端瀏覽器、低版本兼容不友好
const a = 0;
const b = a || 5
//当0作为有效值,与我们期望的 b 的值不一致
console.log(b); // 5
const name = obj?.name;
??=(空值賦值運算符)
let b = '你好';
let a = 0
let c = null;
let d = ’123‘
b ??= a; // b = “你好”
c ??= d // c = '123'
對象解構
解構的對象不能為undefined、null。否則會報錯,所以要給被解構的對象一個默認值。
const {a,b,c,d,e} = obj || {};
合併數組并去重:new Set執行去重操作
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}
拼接字符串
const name = '小明';
const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;
if的巧妙使用
//轉化前
if(
type == 1 ||
type == 2 ||
type == 3 ||
type == 4 ||
){
//...
}
//轉化后
const condition = [1,2,3,4];
if( condition.includes(type) ){
//...
}
數組扁平化
Object.values獲取全部對象的value,flat將所有元素與遍歷到的子數組的元素合併為一個新的數組返回,Infinity則是忽略數組深度
const deps = {
'采购部':[1,2,3],
'人事部':[5,8,12],
'行政部':[5,14,79],
'运输部':[3,64,105],
}
let member = Object.values(deps).flat(Infinity);
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// Expected output: Array [0, 1, 2, Array [3, 4]]
對象添加動態屬性
對象屬性名可以是表達式
let obj = {};
let index = 1;
obj[`topic${index}`] = '话题内容';
輸入框非空判斷
//修改前
if(value !== null && value !== undefined && value !== ''){
//...
}
//修改后
if((value??'') !== ''){
//...
}
多個三目運算符的使用
<span>{{
requirementDetailsimplementwethod ==1
?'业团队实施'
:requirementDetailsimplementwethod == 2
?'自助实施'
:requirementDetailsimplementwethod == 3
?'another':" "
}}</span>
用key管理可復用的元素
該方法下來回切換切換按鈕時,數據仍然保留在input中
<template v-if="type === 'username'">
<label>用户名:</label>
<input placeholder="请输入用户名" />
</template>
<template v-else>
<label>邮箱:</label>
<input placeholder="请输入邮箱" />
</template>
<button
style="margin-left: 12px"
@click="type = type === 'username' ? 'email' : 'username'"
>
切换
</button>
</div>
設置了key值后,每次切換都會對input元素重新渲染
<template v-if="type === 'username'">
<label>用户名:</label>
<input placeholder="请输入用户名" key="username"/>
</template>
<template v-else>
<label>邮箱:</label>
<input placeholder="请输入邮箱" key="email"/>
</template>
<button
style="margin-left: 12px"
@click="type = type === 'username' ? 'email' : 'username'"
>
点击
</button>
查找表模式
把所有策略映射到一個對象中,然後通過鍵來查找對應的策略
const studentStrategy = quantity => quantity > 10 ? 0.8 : 1;
const seniorStrategy = quantity => quantity > 20 ? 0.7 : 1;
const defaultStrategy = () => 1;
const strategies = {
'student': studentStrategy,
'senior': seniorStrategy,
'default': defaultStrategy
};
const calculate = (type, quantity) => {
return (strategies[type] || strategies['default'])(quantity)
}
calculate('student', 15); // 输出: 0.8
使用Map數據解構管理數據
// 创建一个Map对象
const formData = new Map();
// 添加表单元素的值到Map中
formData.set('username', 'John');
formData.set('password', '123456');
// 获取表单元素的值
const username = formData.get('username');
const password = formData.get('password');
管理頁面狀態
const state = new Map();
state.set('loading', false);
state.set('error', null);
state.set('loading', true);
state.set('error', '请求失败');
使用Object.assign()合併對象
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const obj3 = Object.assign({}, obj1, obj2);
console.log(obj3); // 输出:{a: 1, b: 2, c: 3, d: 4}
使用Set去重
使用 new Set(arr) 创建了一个 Set 集合,将数组中的重复元素去除,得到了一个只包含不重复元素的集合。最后,我们使用 Array.from 将集合转换为数组
/* 數組 */
const arr = [1, 2, 3, 2, 1];
const set = new Set(arr);
const uniqueArr = Array.from(set); // [1, 2, 3]
/* 對象去重 */
const arr = [{ id: 1 }, { id: 2 }, { id: 1 }, { id: 3 }];
const set = new Set(arr.map(item => item.id));
const uniqueArr = Array.from(set, id => ({ id }));
console.log(uniqueArr); // [{ id: 1 }, { id: 2 }, { id: 3 }]
偏函數
在这个例子中,我们定义了一个round函数,它接受两个参数:一个函数fn和一个精度precision。round函数返回一个新函数,该函数接受一个值value,并将fn函数应用于该值和精度参数。然后,我们使用round函数来创建一个新函数roundToTwoDecimalsPartial,该函数将roundToTwoDecimals函数绑定到精度2上。最后,我们将这个新函数传递给map方法,从而将数组中的每个元素都四舍五入到两个小数位。
function roundToTwoDecimals(num, precision) {
precision = 10 ** precision;
return Math.round(num * precision) / precision;
}
const numbers = [1.234, 2.345, 3.456];
const round = (fn, precision) => (value) => fn(value, precision);
const roundToTwoDecimalsPartial = round(roundToTwoDecimals, 2);
const roundedNumbers = numbers.map(roundToTwoDecimalsPartial);
console.log(roundedNumbers); // 输出[1.23, 2.35, 3.46]
这里,composedFn表示add、double和square这三个函数组合起来的新函数。我们调用composedFn(1, 2) 时,先将1和2作为参数传递给add函数,得到结果3;然后将3作为参数传递给double函数,得到结果6;最后将6作为参数传递给square函数,得到结果36,这就是整个函数链的最终结果。
const add = (a, b) => a + b;
const double = (x) => x * 2;
const square = (x) => x * x;
const composedFn = compose(square, double, add);
console.log(composedFn(1, 2)); // 输出 36
剪切元素:實現三角形
div {
height: 150px;
width: 150px;
background-color: crimson;
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
debugger
只要在代码中添加debugger,chrome在运行的时候会自动停在那里。还可以用条件语句把它包裹起来,这样就可以在需要的时候才执行它。
if (thisThing) {
debugger;
}
矩陣交換行和列
const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));
transpose(
[ // [
[1, 2, 3], // [1, 4, 7],
[4, 5, 6], // [2, 5, 8],
[7, 8, 9], // [3, 6, 9],
] // ]
);
手機號碼格式化
将手机号码格式化成xxx-xxxx-xxxx的形式
const formatPhone = (str, sign = '-') => str.replace(/(\W|\s)/g, "").split(/^(\d{3})(\d{4})(\d{4})$/).filter(item => item).join(sign)
formatPhone('13123456789') // '131-2345-6789'
formatPhone('13 1234 56 789', ' ') // '131 2345 6789'
重新加載當前頁面
const reload = () => location.reload();
reload()
滾動到頁面底部
const goToTop = () => window.scrollTo(0, 0);
goToTop()
滾動到可視區起點
const scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" })
scrollToTop(document.body)
重定向
const goTo = (url) => (location.href = url);
日期轉換
将日期转换为为 YYYY-MM-DD 格式
const formatYmd = (date) => date.toISOString().slice(0, 10);
formatYmd(new Date())
補零
const replenishZero = (num, len, zero = 0) => num.toString().padStart(len, zero)
replenishZero(8, 2) // 08
JS里实现隐藏和显现
<div id='hidden2'>这里是可以隐藏和显现的区域</div>
<input id='butten' type='butten' οnclick='setChange();'>点击这里</input>
<script>
function setChange(){
$('#hideen2').hide();
$('#hidden2').show();
}
</script>
val():用于將數值字符串轉化為數值
vue3 watch的6中監聽方式
<template>
<h2>当前求和为:{{sum}}</h2>
<button @click="sum++">点我加</button>
<hr>
<h2>{{msg}}</h2>
<hr>
<h2>{{person.name}}</h2>
<h2>{{person.age}}</h2>
<h2>{{person.jap.a.b}}</h2>
<button @click="person.name+='2'">改变名字</button>
<button @click="person.age+=1">改变年龄</button>
<button @click="person.jap.a.b+=1">改变b</button>
</template>
<script>
import {reactive, ref, watch} from 'vue'
export default {
name: "app",
setup() {
let sum = ref(0);
let msg = ref('nihao');
let person = reactive({
name:'张三',
age:123,
jap:{
a:{
b:10
}
}
})
// 情况1,监视ref定义的响应数据
watch(sum,(oldvalue,newvalue)=>{
console.log(oldvalue,newvalue)
},{immediate:true})
// 情况二,监听ref所定义的多个响应式数据
watch([msg,sum],(oldvalue,newvalue)=>{
console.log(oldvalue,newvalue)
},{immediate:true})
//情况三,监听 reactive 所定义的一个响应式数据,注意此处无法获得oldvalue
// 1,注意:此处无法正确的获取oldValue
// 2,注意:强制开启深度监听
watch(person,(oldvalue,newvalue)=>{
console.log(oldvalue,newvalue)
})
//情况四:监听reactive所定义的一个响应式数据中的某个属性
watch(()=>person.name,(oldvalue,newvalue)=>{
console.log(oldvalue,newvalue)
})
//情况五:监听reactive所定义的一个响应式数据中的某些属性
watch([()=>person.name,()=>person.age],(oldvalue,newvalue)=>{
console.log(oldvalue,newvalue)
})
// 情况六:特殊情况
watch(()=>person.jap,(oldvalue,newvalue)=>{
console.log(oldvalue,newvalue)
},{deep:true})//由于此处监视的是reactive所定义的对象中的某个属性,所以deep配置无效
return{
sum,
msg,
person
}
},
};
</script>
<style lang="scss"></style>
利用reduce進行數據解構的轉換
const arr = [ { classId: "1", name: "张三", age: 16 }, { classId: "1", name: "李四", age: 15 }, { classId: "2", name: "王五", age: 16 }, { classId: "3", name: "赵六", age: 15 }, { classId: "2", name: "孔七", age: 16 }];
groupArrayByKey(arr, "classId");
function groupArrayByKey(arr = [], key) {
return arr.reduce((t, v) => (!t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t), {})
}
//結果如下
1. {1: Array(2), 2: Array(2), 3: Array(1)}
1: Array(2)
0: {classId: '1', name: '张三', age: 16}
1: {classId: '1', name: '李四', age: 15}
2: Array(2)
0: {classId: '2', name: '王五', age: 16}
1: {classId: '2', name: '孔七', age: 16}
3: Array(1)
0: {classId: '3', name: '赵六', age: 15}
添加默認值
有时候一个方法需要用户传入一个参数,通常情况下我们有两种处理方式,如果用户不传,我们通常会给一个默认值,亦或是用户必须要传一个参数,不传直接抛错。
function double() {
return value *2
}
// 不传的话给一个默认值0
function double(value = 0) {
return value * 2
}
// 用户必须要传一个参数,不传参数就抛出一个错误
const required = () => {
throw new Error("This function requires one parameter.")
}
function double(value = required()) {
return value * 2
}
double(3) // 6
double() // throw Error
中的v-bind
用于在 SFC 标签中启用组件状态驱动的动态 CSS 值
<script setup>
import { ref, watchEffect } from 'vue';
const color = ref('black')
const callChangeColorHandel = () => {
if(color.value === 'black') {
color.value = 'red'
}else {
color.value = 'black'
}
}
</script>
<style lang="scss" scoped>
.todo-list {
color: v-bind(color);
}
</style>