background

Lu code process will always encounter a lot of scenes, useful black technology to solve, but also useful “strange skills” processing, open post record summary of their own encounter interesting methods

Get the nearest number in the array quickly

Gets a number smaller than itself

const sizeList = [250.16.24.570.30.32.36.40.48.50.60.20.64];

function getValue(size) {
  return (
    size -
    sizeList.reduce(function (closest, v) {
      return size >= v ? Math.min(size - v, closest) : closest;
    }, 1e100)); } getValue(20) / / 16

Copy the code

Get something larger than yourself

function getValue(size) {
  return (
    size +
    sizeList.reduce(function (closest, v) {
      return size <= v ? Math.min(v - size, closest) : closest;
    }, 1e100)); } getValue(20) / / 24
Copy the code

Two, optional chain and exclamation mark use

Optional chain

    let a = {name: 'yi da'.profile: {age: '18'}} a? .profile? .name?.test// Optional chain: '? ': Similar to safeGet in LoDash, the key is fetched only if there are subsequent attributes
Copy the code

Double question mark usage

If a? .profile? Age does not exist, return 100, then?? What is the difference between and | |?

| | 0 / false if the previous conditions, will return back. ?? Return null and undefined only if the current is null and undefined.

    constvalue = a? .profile? .age ??100 / / 18
Copy the code

The clever use of the exclamation mark in TS

    let a = {name: 'yi da'.profile: {age: '18'}} a! .profile! .age// Confirm function chain,! . Indicates that the corresponding attribute must exist
    funtion test(){
        // ts
        returnname! ;// Indicates that name must not be null/undefined
    }
Copy the code