2024年07月23日 建站教程
前端入门需要了解的几个js小知识,比如找出总和、最小值、最大值、声明和初始化数组、filter过滤出数组中虚假值等等。
1、reduce找出总和、最小值和最大值
//reduce函数 const array = [5,4,7,8,9,2]; //求和 array.reduce((a,b) => a+b); // 输出: 35 //找出最大 array.reduce((a,b) => a>b?a:b); // 输出: 9 //找出最小 array.reduce((a,b) => a<b?a:b); // 输出: 2
2、声明和初始化数组
const array = Array(5).fill(''); // 输出 (5) ["", "", "", "", ""] const matrix = Array(5).fill(0).map(()=>Array(5).fill(0)); // 输出 (5) [Array(5), Array(5), Array(5), Array(5), Array(5)] 0: (5) [0, 0, 0, 0, 0] 1: (5) [0, 0, 0, 0, 0] 2: (5) [0, 0, 0, 0, 0] 3: (5) [0, 0, 0, 0, 0] 4: (5) [0, 0, 0, 0, 0] length: 5
3、sort()和reverse()对字符串、数字或对象数组进行排序
//排序数字数组 const array = [40, 100, 1, 5, 25, 10]; array.sort((a,b) => a-b); // 输出 (6) [1, 5, 10, 25, 40, 100] array.sort((a,b) => b-a); // 输出 (6) [100, 40, 25, 10, 5, 1] //排序字符串数组 const stringArr = ["Joe", "Kapil", "Steve", "Musk"] stringArr.sort(); // 输出 (4) ["Joe", "Kapil", "Musk", "Steve"] stringArr.reverse(); // 输出 (4) ["Steve", "Musk", "Kapil", "Joe"] //对象数组排序 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
filter过滤出数组中虚假值
const array = [3, 0, 6, 7, '', false]; array.filter(Boolean); // 输出 (3) [3, 6, 7]
删除重复值
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]
对各种条件使用逻辑运算符
function doSomething(arg1){ arg1 = arg1 || 10; // 如果尚未设置,则将 arg1 设置为 10 作为默认值 return arg1; } let foo = 10; foo === 10 && doSomething(); // is the same thing as if (foo == 10) then doSomething(); // 输出: 10 foo === 5 || doSomething(); // is the same thing as if (foo != 5) then doSomething(); // 输出: 10
合并多个对象
const user = { name: '小李', gender: '一级' }; const college = { primary: '大专', secondary: 'A级' }; const skills = { programming: '12', swimming: '32', sleeping: 'aa' }; const summary = {...user, ...college, ...skills};
Math.random()打乱数组
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; list.sort(() => { return Math.random() - 0.5; }); // 输出 (9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
空合并运算符 (??)
const foo = null ?? 'my school'; // 输出: "my school" const baz = 0 ?? 42; // 输出: 0
单行回文检查
function checkPalindrome(str) { return str == str.split('').reverse().join(''); } checkPalindrome('naman'); // 输出: true
将Object属性转成属性数组
使用Object.entries(),Object.keys()和Object.values() const obj = { a: 1, b: 2, c: 3 }; Object.entries(obj); // 输出 (3) [Array(2), Array(2), Array(2)] 0: (2) ["a", 1] 1: (2) ["b", 2] 2: (2) ["c", 3] length: 3 Object.keys(obj); (3) ["a", "b", "c"] Object.values(obj); (3) [1, 2, 3]
本文链接:http://so.lmcjl.com/news/9022/