10个你每天都需要用到的Javascript代码片段
新墨科技-web前端开发 / 2021-04-11 18:43:42
1、遍历对象
// Simple way
const person = { name: "Shoaib", Age: 25, Gender: "Male" };
for (const property in person) {
console.log(`${property}: ${person[property]}`);
}
// Another way
const anotherPerson = {
Name: 'Shoaib',
Age: 25,
Gender:"Male"
};
for (const [key, value] of Object.entries(anotherPerson)) {
console.log(`${key}: ${value}`);
}
2、查找对象数组
进入阵列是日常开发或编程中最需要完成的任务。在这里,我们使用find函数来执行此操作。该功能也适用于其他阵列。数字数组,对象数组,字符串数组,所有内容都支持此方法。
代码如下:
const students = [
{name: 'Shoaib', roll: 2},
{name: 'Mehedi', roll: 10},
{name: 'Alex', roll: 5}
];
function search(student) {
return student.name=== "Mehedi";
}
console.log(students.find(search));
// { name: 'Mehedi', roll: 10 }
3、对数组排序
对数组进行排序是一个令人困惑且经常使用的代码段。Javascript具有其内置sort()功能。此方法适用于字母排序。因此,针对数字的解决方案是添加一个处理数字类型的新方法。在这里,我描述了字母排序和数字排序。
注意:在期望数值排序时,请不要忘记使用新方法。
// sort alphabetically
const name = ['Shoaib', 'Mehedi', 'Alex', 'Jane'];
const arr = [1, 30, 4, 21, 100000];
name.sort();
console.log(name);
// sort numerically
上一篇:8种现代数组方法,每个开发人员都应该知道 下一篇:来了,不限速网盘PC客户端
热门文章
最新文章
推荐文章