JS操做小技巧,工做简单了

1、Optional Chaining

在javaScript中,对象的属性链访问,很容易由于某一个属性不存在出现 Cannot read property 'xxx' of undefined的问题,那么Optional Chaining就添加了?.操做符,它会先判断前面的值,若是undefined或者null,就结束后面的调用,直接返回undefined; java

1.1 访问深度嵌套的属性

const obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
};

const baz = obj?.foo?.bar?.baz; // 42

const safe = obj?.qux?.baz; // undefined

// Optional chaining and normal chaining can be intermixed
obj?.foo.bar?.baz; // Only access `foo` if `obj` exists, and `baz` if
                   // `bar` exists

// Example usage with bracket notation:
obj?.['foo']?.bar?.baz // 42
复制代码

1.2 调用深层嵌套的函数

const obj = {
  foo: {
    bar: {
      baz() {
        return 42;
      },
    },
  },
};

const baz = obj?.foo?.bar?.baz(); // 42

const safe = obj?.qux?.baz(); // undefined
const safe2 = obj?.foo.bar.qux?.(); // undefined

const willThrow = obj?.foo.bar.qux(); // Error: not a function

// Top function can be called directly, too.
function test() {
  return 42;
}
test?.(); // 42

exists?.(); // undefined
复制代码

1.3 构造深层嵌套的类

const obj = {
  foo: {
    bar: {
      baz: class {
      },
    },
  },
};

const baz = new obj?.foo?.bar?.baz(); // baz instance

const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined

const willThrow = new obj?.foo.bar.qux(); // Error: not a constructor

// Top classes can be called directly, too.
class Test {
}
new Test?.(); // test instance

new exists?.(); // undefined
复制代码

1.4 安装使用

  • 安装:
npm install --save-dev @babel/plugin-proposal-optional-chaining
yarn add @babel/plugin-proposal-optional-chaining --dev
复制代码
  • 配置.babelrc:
{
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}
复制代码

2、随机生成字母和数组的组合

Math.random().toString(36).substr(2);
复制代码

3、转换布尔值

const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;
console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"
复制代码

4、转换数字

let number = '10';
number = +number;
console.log(number); // 10
复制代码
let number = '10';
number = ~~number;
console.log(number); // 10
复制代码

5、替代Math.pow

console.log(Math.pow(2, 3));
// 替代1
console.log(2 ** 3);
// 替代二,只能以二做为基数
console.log(2 << (3 - 1));
复制代码

6、快速浮点数转整数

console.log(10.9 | 0);  // 10
console.log(-10.9 | 0); // 10
复制代码

console.log(~~10.9);
console.log(~~-10.9); 
复制代码

7、数组降维度

二维数组npm

let arr = [ [1], [2], [3] ];
arr = Array.prototype.concat.apply([], arr);
console.log(arr);// [1, 2, 3]

let array = [ [1], [2], [3] ];
array = array.flat(2);
console.log(array); // [1, 2, 3]
复制代码

多维数组数组

let arrMore = [1, 2, [3], [[4]]];
arrMore = arrMore.flat(Infinity);
console.log(arrMore);
复制代码

8、判断小数是否相等

console.log(0.1 + 0.2  === 0.3); // false
复制代码
function equal(number1, number2) {
    return Math.abs(number1 - number2) < Math.pow(2, -52);
}
console.log(equal(0.1 + 0.2, 0.3));
复制代码

9、判断变量是不是数组

1. instanceof
2. array.__proto__.constructor === Array
3. array.constructor === Array
4. Array.isArray(兼容性问题)
5. Object.prototype.toString.call([]) === "[object Array]"(最通用)
复制代码

PS:instanceof和constructor判断的变量,必须在当前页面声明。例如:父页面是一个框架,框架中引入一个页面(子页面),在子页面中申明的array,并将其复制给父元素的一个变量,这时instanceof和constructor判断该变量,将返回false。 ----------------------------------------------------------------------------------------------------------------- 缘由: array是复合类型。在传递的过程当中,仅仅是引用地址的传递。 每一个页面的array原生对象引用的地址是不同的,在子页面中声明的array,所对应的构造函数,是子页面的array对象,在父页面进行判断时,使用的并非子页面的array。 bash

10、数组占位

let array = Array(3).fill('');
console.log(array); //["", "", ""]
复制代码

11、数组去重多重方式

11.1 Set(最经常使用)

Array.prototype.unique = function() {
    return [...new Set(this)];
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique();
复制代码

11.2 Map

Array.prototype.unique = function() {
    const tmp = new Map();
    return this.filter(item => {
        return !tmp.has(item) && tmp.set(item, 1);
    })
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique();
复制代码

11.3 Array.prototype.indexOf()

Array.prototype.unique = function() {
    return this.filter((item, index) => {
        return this.indexOf(item) === index;
    })
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique();
复制代码

11.4 Array.prototype.includes()

Array.prototype.unique = function() {
    const newArray = [];
    this.forEach(item => {
        if (!newArray.includes(item)) {
            newArray.push(item);
        }
    });
    return newArray;
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique();
复制代码

11.5 Array.prototype.reduce()

Array.prototype.unique = function() {
    return this.sort().reduce((init, current) => {
        if (init.length === 0 || init[init.length - 1] !== current) {
            init.push(current);
        }
        return init;
    }, []);
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique();

复制代码

12、短路运算(&& ||)

使用&&将返回第一个条件为假的值。若是每一个操做数的计算值都为true,则返回最后一个计算过的表达式。babel

let one = 1, two = 2, three = 3;
console.log(one && two && three); // 3
console.log(0 && null); // 0
复制代码

使用||将返回第一个条件为真的值。若是每一个操做数的计算结果都为false,则返回最后一个计算过的表达式。markdown

let one = 1, two = 2, three = 3;
console.log(one || two || three); // 1
console.log(0 || null); // null
复制代码

十3、过滤空值

let result1 = [1, 2, 0, undefined, null, false, ''].filter(Boolean);
console.log(result1);
复制代码

十4、建立空对象

let dict = Object.create(null);
复制代码

十5、合并对象

const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };
const summary = { ...person, ...tools, ...attributes };
console.log(summary);
复制代码

十6、字符串去空格

String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};
复制代码

十7、对象转换为数组

var argArray = Array.prototype.slice.call(arguments);
复制代码

十8、逗号操做符

var a = 0; 
var b = ( a++, 99 ); 
console.log(a);  
console.log(b);
复制代码

十9、 localStorage.getItem('key') === localStorage.key

来源: 沉末_评论。app

localStorage.setItem('item', 1);
localStorage.getItem('item') === localStorage.item;
复制代码

二10、从一堆文本中获取手机号

来源: 飞蛾扑火评论。框架

([\s,,、]*)?((手机|联系方式|电话|联系人)号?)?(号码)?([、::\s]*)?(?:[\s((]*?\+?(86)?[\s))]*)(1\d{2})(?:[-\s]*)(\d{4})(?:[-\s]*)(\d{4})(?=\D|$)
复制代码

二11、整数变量交换

来源: 快乐的仲子评论。dom

let a = 10;
let b = 50;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(a, b); // 50 10
复制代码

二12、整数变量交换

var a = 2;
var b = 4;
a = a + b;
b = a - b;
a = a - b;
console.log(a, b); // 4 2
复制代码

二十3、整数变量交换

来源: 醉倒丶你怀里评论。函数

let a = 10;
let b = 50;
[a,b]=[b,a]
console.log(a);
console.log(b)
复制代码

二十4、快速生成一个递增数组

来源: 彩虹Rainbow评论。

Array.from({length: 10},(val, index)=>index);
// [0,1,2,3,4,5,6,7,8,9,10]
复制代码

评论出你的“奇人异巧”,让你们都学习。

参考:

相关文章
相关标签/搜索