将String类型的数组转为Number类型:a.map(Number)
将Number类型的数组转为String类型:a.map(String)
let a = ['1', '2', '3'];
let b = [4, 5, 6];
console.log(a.map(Number))
console.log(b.map(String))
打印结果:
替换字符串中指定字符: a.replace(/指定字符/,'替换后的字符')
var str = "Visit Microsoft!"
let key = str.replace(/Visit/, "My");
console.log(key)
//输出:My Microsoft!
求数组中的最大值:Math.max([...arr])
求数组中的最小值:Math.min([...arr])
let num = [1,9,2,5,20,4]
let max = Math.max(...num)
let min = Math.min(...num)
console.log(max)//输出:20
console.log(min)//输出:1
对两数组对象的指定值进行过滤:filter()
//删除两数组对象中相同id的对象
let a = [
{ id: 1, name: 'aa' },
{ id: 2, name: 'bb' },
{ id: 3, name: 'cc' }
]
let b = [
{ id: 1, name: 'dd' },
{ id: 2, name: 'ff' },
]
//删除a数组对象中跟b相同id的对象
let ary = a.filter(item => !b.some(ele => ele.id === item.id));
console.log(ary)
//输出 [{ id: 3, name: 'cc' }]
筛选两个数组间id相同的数对象:
let a = [
{ id: 1, name: 'aa' },
{ id: 2, name: 'bb' },
{ id: 3, name: 'cc' }
]
let b = [1, 2]
// 保留a数组中id跟b相同的对象
let ary = a.filter(t => b.includes(t.id))
console.log(ary)
// 输出 [{ id: 1, name: 'aa' },{ id: 2, name: 'bb' }]
删除对象中的指定属性 ↓
// 例如需要得到一个新对象,里面删除num、descript两个属性↓
let ary = {
id: 1,
name: 'aa',
num: 44,
descript: '测试测试',
create_time: '2022-06-15 15:17:30'
}
const { num, descript, ...rest } = ary
console.log(rest)
// 输出:{id: 1, name: 'aa', create_time: '2022-06-15 15:17:30'}
生成长度为10,数字为0-9的数组:Array.from()
let arr = Array.from({ length: 10 }).map((t, i) => {
return i;
});
console.log(arr);
//输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]