掌握20个JS技巧

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

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:用??代替||,用于判断运算符左侧的值为null或undefined时,才返回右侧的值

它的行为类似||,但是更严
||运算符是左边是空字符串或false或0等falsy值,都会返回后侧的值。
而??必须运算符左侧的值为null或undefined时,才会返回右侧的值。因此0||1的结果为1,0??1的结果为0

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false

掌握20个JS技巧_第1张图片

6:使用String.prototype.replaceAll()简化replace一次性替换所有子字符串

// 以前
console.log('aaa'.replace(/a/g,'A')) //AAA

// 简化后
console.log('aaa'.replaceAll('a','A')) //AAA

掌握20个JS技巧_第2张图片

7:函数防抖:
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
使用场景:
input框边输入边调取接口,
用户频繁的点击提交按钮,像服务器发送数据。
onscroll,鼠标滑动事件等。

export const Debounce = (fn, t) => {
    let delay = t || 500
    let timer
    return function () {
        let args = arguments;
        if (timer) {
            clearTimeout(timer)
        }

        let callNow = !timer

        timer = setTimeout(() => {
            timer = null
        }, delay)

        if (callNow) fn.apply(this, args)
    }
}

onSubmit: Debounce(function() {
                let paramsData = {
                    ...this.formList,
                    authorization: this.token
                }
                // console.log('提交代码', paramsData)
                let that = this;
                saveGlxx(paramsData).then((res) => {
                        if (res.success == true) {
                            that.formList = Object.assign({}, that.formList, that.$options.data().formList)
                            Toast.success('提交成功');
                        }
                    })
                    .catch((err) => {
                        Toast.fail('系统异常,请稍后再试!');
                    })
}, 1000),

8:格式化金钱

const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const money = ThousandNum(20190214);
// money => "20,190,214"

9: es6去重

let uniqueArray = [...new Set([1, 2, 3, 3, 3,"school","school", 'ball', false, false, true, true])];

// >>> [1, 2, 3, "school", "ball", false, true]

10: if多条件判断
includes() 方法确定数组是否包含指定的元素。

A:
 var x = 'ghi'
// 冗余
if (x === 'abc' || x === 'def' || x === 'ghi' || x === 'jkl') {}
// 简写
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
    console.log('成立')
} else {
    console.log('不成立')
}

B: 检查数组中是否包含某一项
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
console.log('n', n); //true

11: Null, Undefined, 空值检查

// 冗余
if (first !== null || first !== undefined || first !== '') {
    let second = first;
}

// 简洁
let second = first || '';

12:隐式返回

// 冗余
function getArea(diameter) {
      return 5 * diameter
}
        
// 简洁
getArea = diameter => (
      5 * diameter
)
// 简写
getArea = diameter =>5 * diameter;

13:

你可能感兴趣的:(javascript前端)