前端写代码中经常用到的数组和对象方法汇总

目录

数组查找元素

数组转字符串

字符串转数组 

对象转数组

对象的深拷贝

对象的遍历

对象合并 


文章参考自MDNJavaScript | MDN


数组查找元素

是否存在:Array.prototype.includes()

//includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

满足一定条件的并返回值:Array.prototype.find ()

//find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

 满足一定条件的并返回下标:Array.prototype.findIndex()

//findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

数组转字符串

Array.prototype.join()

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

字符串转数组 

String.prototype.splite()

const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');//这里传了空格分隔符
console.log(words);
//expected output:["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]

对象转数组

Object.entries()

const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

对象的深拷贝

JSON.parse(JSON.stringify(state.category))
先转成json再转成对象
//JSON.stringify() 方法将一个 JavaScript 对象或值转换为 JSON 字符串

console.log(JSON.stringify({ x: 5, y: 6 }));
// expected output: "{"x":5,"y":6}"


//JSON.parse() 方法用来解析JSON字符串,构造由字符串描述的JavaScript值或对象。
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj);
// expected output: { result: true, count: 42 }

对象的遍历

for...in

//for ... in是为遍历对象属性而构建的,它最常用的地方应该是用于调试,可以更方便的去检查对象属性

对象合并 

Object.assign()

//Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。返回值是目标对象。
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值