JS的小技巧

123 阅读3分钟

document.designMode

与前端的JavaScript有关,设计模式让你可以编辑页面上的任何内容。只要打开浏览器控制台,输入以下内容即可。

document.designMode = 'on';

replaceAll 方法

在 JS 中,要将所有出现的字符串替换为另一个字符串,我们需要使用如下所示的正则表达式:

const str = 'Red-Green-Blue';

// 只规制第一次出现的
str.replace('-', ' '); // Red Green-Blue

// 使用 RegEx 替换所有匹配项
str.replace(/-/g, ' '); // Red Green Blue

检查属性是否存在对象中

可以使用 in 关键字来检查 JavaScript 对象中是否存在某个属性。

const person = { name: '小明', salary: 1000 };
console.log('salary' in person); // true
console.log('age' in person); // false

空值合并 ?? 操作符

当我们想检查一个变量是否为 null 或 undefined 时,??操作符很有用。当它的左侧操作数为null 或 undefined时,它返回右侧的操作数,否则返回其左侧的操作数。

const foo = null ?? 'Hello';
console.log(foo); // 'Hello'

const bar = 'Not null' ?? 'Hello';
console.log(bar); // 'Not null'

const baz = 0 ?? 'Hello';
console.log(baz); // 0

在第三个示例中,返回 0,因为即使 0 在 JS 中被认为是假的,但它不是null的或undefined的。你可能认为我们可以用||算子但这两者之间是有区别的

你可能认为我们可以在这里使用 || 操作符,但这两者之间是有区别的。

const cannotBeZero = 0 || 5;
console.log(cannotBeZero); // 5

const canBeZero = 0 ?? 5;
console.log(canBeZero); // 0

可选链 .?

我们是不是经常遇到这样的错误:TypeError: Cannot read property ‘foo’ of null。这对每一个毅开发人员来说都是一个烦人的问题。引入可选链就是为了解决这个问题。一起来看看

const book = { id:1, title: 'Title', author: null };

// 通常情况下,你会这样做
console.log(book.author.age) // throws error
console.log(book.author && book.author.age); // null

// 使用可选链
console.log(book.author?.age); // undefined
// 或深度可选链
console.log(book.author?.address?.city); // undefined
```

还可以使用如下函数可选链:

```
const person = {
  firstName: '前端',
  lastName: '小明',
  printName: function () {
    return `${this.firstName} ${this.lastName}`;
  },
};
console.log(person.printName()); // '前端 小明'
console.log(persone.doesNotExist?.()); // undefined

Object.entries

大多数开发人员使用 Object.keys 方法来迭代对象。此方法仅返回对象键的数组,而不返回值。我们可以使用 Object.entries 来获取键和值。

const person = {
  name: '前端小明',
  age: 20
};

Object.keys(person); // ['name', 'age']
Object.entries(data); // [['name', '前端小明'], ['age', 20]]

为了迭代一个对象,我们可以执行以下操作:

Object.keys(person).forEach((key) => {
  console.log(`${key} is ${person[key]}`);
});

// 使用 entries 获取键和值
Object.entries(person).forEach(([key, value]) => {
  console.log(`${key} is ${value}`);
});

// name is 
// age is 20 

获取url参数

function getRequestUrl() {
    var url = location.search;
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for(var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

采用正则表达式获取地址栏参数

function GetQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}
 
// 调用方法
alert(GetQueryString("参数名1"));
alert(GetQueryString("参数名2"));
alert(GetQueryString("参数名3"));

获取url参数转为对象

 // 地址栏参数转为对象
      function toObj(params) {
          let oneSp = params.split("&")
          let resultObj = {}
          oneSp.forEach(item => {
            const a = item.split("=")
            resultObj[a[0]] = a[1]
          })
          return resultObj
      }

      const str = "a=1";
      console.log(toObj(str));

排序

注意,如果数字按照字符串来排序,则 "25" 大于 "100",因为 "2" 大于 "1"。 正因如此,sort() 方法在对数值排序时会产生不正确的结果。

所以要使用-比值函数来修正此问题:
var points = [40, 100, 1, 5, 25, 10];
1、从大到小:points.sort(function(a, b){return b - a}); 
	[100, 40, 25, 10, 5, 1]
2、从小到大:points.sort(function(a, b){return a - b}); 
 	[1, 5, 10, 25, 40, 100]

数组对象排序:
var cars = [{type:"Volvo", year:2016},{type:"Saab", year:2001},{type:"BMW", year:2010}]

1、从小到大:
cars.sort(function(a, b){return a.year - b.year})
  [  0: {type: "Saab", year: 2001}     1: {type: "BMW", year: 2010}     2: {type: "Volvo", year: 2016}  ]
2、从大到小
cars.sort(function(a, b){return b.year - a.year})
[0: {type: "Volvo", year: 2016}1: {type: "BMW", year: 2010}2: {type: "Saab", year: 2001}]

数组与字符串之间的相互转换

传入需要合并的,并逗号分割

 let arr = [
      { name: "小明", age: 18, hippy: "111" },
      { name: "小红", age: 19, hippy: "222" },
      { name: "小雪", age: 20, hippy: "222" },
    ];
    let fields = ["name", "age", "hippy"];

    function getData(arr, fields) {
      let hash = Object.create({});
      arr.forEach((item) => {
        fields.forEach((field) => {
          if (!hash[field]) {
            hash[field] = [];
          }
          hash[field].push(item[field]);
        });
      });
      for (let prop in hash) {
        hash[prop] = hash[prop].join(",");
      }
      return hash;
    }
    let dd = getData(arr, fields);
    console.dir(dd);

 // 将所有的相同属性合并成字符串,逗号分割
    var arrs = [{
      name: '小米',
      age: 12,
      a:1
    }, {
      name: '小张',
      age: 18,
      a:2
    }]
    let st = arrs.reduce((pre, cur, index, arr) => {
      Object.keys(cur).forEach(key => {
        pre[key] = (pre[key] ? pre[key] + ',' : '') + cur[key]
      })
      return pre;
    }, {})
    console.log(st)

  // 逗号 分割 转为数组
    const str = '小明,小红,小雪'
    function zhuanArr() {
      let stringArr = []
      const strList = str.split(',');
      strList.forEach(item => {
        const obj = {};
        obj.name = item
        stringArr.push(obj)
      })
      return stringArr
    }
    // console.log(zhuanArr(str));