共计 1428 个字符,预计需要花费 4 分钟才能阅读完成。
1:找出数组中总和,最大值,最小值
const array = [5,4,7,8,9,2];
console.log('总和', array.reduce((a, b) =>a+b)); //35
console.log('最大值', array.reduce((a,b) => a>b?a:b)); //9
console.log('最小值', array.reduce((a,b) => a<b?a:b)); //2
2: 对字符串,数字或对象数组进行排序
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
console.log('排序 1', stringArr.sort()); // ['Joe', 'Kapil', 'Musk', 'Steve']
// 排序数字数组
const array = [40, 100, 1, 5, 25, 10];
console.log('排序数字数组', array.sort((a, b) => a - b));
//[1, 5, 10, 25, 40, 100]
// 从大到小
console.log('从大到小', array.sort((a,b) => b-a));
//[100, 40, 25, 10, 5, 1]
// 对象数组排序
const objectArr = [{ first_name: 'Lazslo', last_name: 'Jamf'},
{first_name: 'Pig', last_name: 'Bodine'},
{first_name: 'Pirate', last_name: 'Prentice'}
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输入
(3) [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3
3: 删除反复值
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// 输入: [5, 4, 7, 8, 9, 2]
4:合并多个对象
const user = {
name: 'Kapil Raghuwanshi',
gender: 'Male'
};
const college = {
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = {
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};
const summary = {
...user,
...college,
...skills
};
console.log('summar', summary);
// 输入
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"
5:
正文完
发表至: javascript
2022-03-22