常用的前端(数组或对象等)操作技巧 -- 随记持续更新

背景:

在前端开发过程中,经常需要对数组和对象进行一些常用操作,下边是平常用到的一些常用方法随时记录随时记录更新


数组保留首位元素:

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

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值