美文网首页
5 分钟掌握 JavaScript 实用窍门

5 分钟掌握 JavaScript 实用窍门

作者: 简书超级会员 | 来源:发表于2018-06-25 10:40 被阅读9次

简评:一开始 JavaScript 只是为网页增添一些实时动画效果,现在 JS 已经能做到前后端通吃了,而且还是年度流行语言。本文分享几则 JS 小窍门,可以让你事半功倍 ~

1.删除数组尾部元素

一个简单方法就是改变数组的 length 值:

const arr = [11, 22, 33, 44, 55, 66];
// truncanting
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefined
2.使用对象解构来处理数组

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

// 以前,为变量赋值,只能直接指定值。

let a = 1;
let b = 2;
let c = 3;
// ES6 允许写成下面这样。

let [a, b, c] = [1, 2, 3];

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

对象解构

let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined

字符串解构

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

let {length : len} = 'hello';
len // 5
const csvFileLine = '1997,John Doe,US,john@doe.com,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.创建 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
5.格式化 JSON 代码

JSON.stringify除了可以将一个对象字符化,还可以格式化输出 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"
// =>        }
// =>    }
// =>}"
6.从数组中移除重复元素

通过使用集合语法和 Spread 操作,可以很容易将重复的元素移除:

const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]
7.平铺多维数组

使用 Spread 操作平铺嵌套多维数组:

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]

希望这些小技巧能帮助你写好 JavaScript ~

相关文章

网友评论

      本文标题:5 分钟掌握 JavaScript 实用窍门

      本文链接:https://www.haomeiwen.com/subject/wsweyftx.html