背景:
在前端开发过程中,经常需要对数组和对象进行一些常用操作,下边是平常用到的一些常用方法随时记录随时记录更新
数组保留首位元素:
let myArray = [1, 2, 3, 4, 5];
let newArray = myArray.slice(0, 1);
console.log(newArray); // 输出 [1]
数组保留末位元素:
let myArray = [1, 2, 3, 4, 5];
let newArray = myArray.slice(-1);
console.log(newArray); // 输出 [5]
数组去除首位元素:
let myArray = [1, 2, 3, 4, 5];
myArray.shift();
console.log(myArray); // 输出 [2, 3, 4, 5]
数组去除末位元素:
let myArray = [1, 2, 3, 4, 5];
myArray.pop();
console.log(myArray); // 输出 [1, 2, 3, 4]
取父级传参:
project_name: this.$route.query.project_name,
指向当前页面ref:
this.$refs.table.refresh();
判断数组是否为空:
if (this.myArray.length === 0) {
console.log('数组为空');
} else {
console.log('数组不为空');
}
取对象的key:
const data = {
"28A1BBA6E1F34E839F298AC721727BEF": [
{
"actoridname": "刘永"
},
{
"actoridname": "刘永"
},
{
"actoridname": "刘永"
}
],
};
const arrayNames = Object.keys(data);
数组元素去重:
const myArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(myArray)];
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
对象属性的动态访问:
const data = {
name: 'John',
age: 25,
};
const propertyName = 'name';
console.log(data[propertyName]); // 输出 'John'
条件判断简化:
// 使用三元运算符
const result = condition ? value1 : value2;
// 使用逻辑运算符
const result = condition && value1 || value2;
字符串转换为数字:
const str = '123';
const num = Number(str);
console.log(num); // 输出 123
字符串模板替换:
const name = 'John';
const message = `Hello, ${name}!`;
console.log(message); // 输出 'Hello, John!'
利用解构赋值获取对象属性:
const user = {
name: 'John',
age: 25,
};
const { name, age } = user;
console.log(name, age); // 输出 'John' 25
数组和对象的深拷贝:
// 数组深拷贝
const originalArray = [1, 2, 3];
const copiedArray = JSON.parse(JSON.stringify(originalArray));
// 对象深拷贝
const originalObject = { name: 'John', age: 25 };
const copiedObject = JSON.parse(JSON.stringify(originalObject));