JS一些 实用窍门

1. 删除数组尾部元素

const arr = [11, 22, 33, 44, 55, 66];
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefined

2.使用对象解构来处理数组

可以使用对象解构的语法来获取数组的元素:

const csvFileLine = '1997,John Doe,US,[email protected],New York';
const { 2: country, 4: state } = csvFileLine.split(',');

3.在 Switch 语句中使用范围值

function getWaterState(tempInCelsius) {
  let state;
  switch (true) {
    case (tempInCelsius  0):
      state = 'Solid';
      break;
    case (tempInCelsius > 0 && tempInCelsius <100):
      state = 'Liquid';
      break;
    default:
      state = 'Gas';
  }
  return state;
}

4.await 多个 async 函数

在使用 async/await 的时候,可以使用 Promise.all await 多个 async 函数

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])

5.创建 pure objects

可以创建一个 100% pure object,它不从Object中继承任何属性或则方法(比如constructor, toString()等)

const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined

6.格式化 JSON 代码

const obj = {
  foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } }
};
// The third parameter is the number of spaces used to
// beautify the JSON output.
JSON.stringify(obj, null, 4);
// =>"{
// =>    "foo": {
// =>        "bar": [
// =>            11,
// =>            22,
// =>            33,
// =>            44
// =>        ],
// =>        "baz": {
// =>            "bing": true,
// =>            "boom": "Hello"
// =>        }
// =>    }
// =>}"

7.从数组中移除重复元素

const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]

8.平铺多维数组

const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]

不过上面的方法仅适用于二维数组,但是通过递归,就可以平铺任意维度的嵌套数组了:

function flattenArray(arr) {
  const flattened = [].concat(...arr);
  return flattened.some(item => Array.isArray(item)) ?
    flattenArray(flattened) : flattened;
}
const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenArray(arr);
//=> [11, 22, 33, 44, 55, 66, 77, 88, 99]

猜你喜欢

转载自blog.csdn.net/cao_dan/article/details/81705154