6、删除重复值
您可能已经将 indexOf() 与for 循环一起使用,该循环返回第一个找到的索引或较新的 includes() 从数组中返回布尔值 true/false 以找出/删除重复项。 这是我们有两种更快的方法。
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]
7、创建计数器对象或映射
大多数情况下,需要通过创建计数器对象或映射来解决问题,该对象或映射将变量作为键进行跟踪,并将其频率/出现次数作为值进行跟踪。
let string = 'kapilalipak';
const table={};
for(let char of string) {
table[char]=table[char]+1 || 1;
}
// 输出
{k: 2, a: 3, p: 2, i: 2, l: 2}
和
const countMap = new Map();
for (let i = 0; i < string.length; i++) {
if (countMap.has(string[i])) {
countMap.set(string[i], countMap.get(string[i]) + 1);
} else {
countMap.set(string[i], 1);
}
}
// 输出
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}
8、三元运算符很酷
您可以避免使用三元运算符嵌套条件 if…elseif…elseif。
function Fever(temp) {
return temp > 97 ? 'Visit Doctor!'
: temp < 97 ? 'Go Out and Play!!'
: temp === 97 ? 'Take Some Rest!';
}
// 输出
Fever(97): "Take Some Rest!"
Fever(100): "Visit Doctor!"
9、与旧版相比,for 循环更快
for并for…in默认为您提供索引,但您可以使用 arr[index]。
for…in 也接受非数字,所以避免它。
forEach,for…of直接获取元素。
forEach也可以为您提供索引,但for…of不能。
for并for…of考虑阵列中的孔,但其他 2 个不考虑。
10、合并2个对象
通常我们需要在日常任务中合并多个对象。
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};
// 输出
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了一些实用的提高javasript代码效率的小窍门