您好,欢迎访问一九零五行业门户网

很重要的9个使用技巧(附代码)

这次给大家带来很重要的9个使用技巧(附代码),js使用的注意事项有哪些,下面就是实战案例,一起来看一下。
1. 删除数组尾部元素
一个简单的用来清空或则删除数组尾部元素的简单方法就是改变数组的length属性值。
const arr = [11, 22, 33, 44, 55, 66];// truncantingarr.length = 3;console.log(arr); //=> [11, 22, 33]// clearingarr.length = 0;console.log(arr); //=> []console.log(arr[2]); //=> undefined
2.使用对象解构来模拟命名参数
如果你需要将一系列可选项作为参数传入函数,那么你也许倾向于使用了一个对象(object)来定义配置(config)。
dosomething({ foo: 'hello', bar: 'hey!', baz: 42 });function dosomething(config) { const foo = config.foo !== undefined ? config.foo : 'hi'; const bar = config.bar !== undefined ? config.bar : 'yo!';  const baz = config.baz !== undefined ? config.baz : 13;  // ...}
这是一个陈旧、但是很有效的方法,它模拟了javascript中的命名参数。不过呢,在dosomething中处理config的方式略显繁琐。在es2015中,你可以直接使用对象解构。
function dosomething({ foo = 'hi', bar = 'yo!', baz = 13 }) { // ...}
如果你想让这个参数是可选的,也很简单。
function dosomething({ foo = 'hi', bar = 'yo!', baz = 13 } = {}) { // ...}
3. 使用对象解构来处理数组
可以使用对象解构的语法来获取数组的元素:
const csvfileline = '1997,john doe,us,john@doe.com,new york';const { 2: country, 4: state } = csvfileline.split(',');
4. 在switch语句中用范围值
可以使用下面的技巧来写满足范围值的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;}
5. await多个async函数
在使用async/await的时候,可以使用promise.all来await多个async函数。
await promise.all([anasynccall(), thisisalsoasync(), onemore()])
6. 创建一个纯(pure)对象
你可以创建一个100%的纯对象,他不从object中继承任何属性或则方法(比如,constructor,tostring()等等)。
const pureobject = object.create(null);console.log(pureobject); //=> {}console.log(pureobject.constructor); //=> undefinedconsole.log(pureobject.tostring); //=> undefinedconsole.log(pureobject.hasownproperty); //=> undefined
7. 格式化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// =>    }// =>  }// =>}
8. 从数组中移除重复元素
es2015中,有了集合的语法。通过使用集合语法和spread操作,可以很容易将重复的元素移除:
const removeduplicateitems = arr => [...new set(arr)];removeduplicateitems([42, 'foo', 42, 'foo', true, true]);//=> [42, foo, true]
9. 平铺多维数组
使用spread操作,可以很容易去平铺嵌套多维数组:
const arr = [11, [22, 33], [44, 55], 66];const flatarr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]
可惜,上面的方法仅仅适用于二维数组。不过,通过递归,我们可以平铺任意维度的嵌套数组。
unction 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]
就这些啦!我希望这些小技巧可以帮你写出更加漂亮的js代码!如果还不够,那么不妨用fundebug做你的辅助!
精选评论
ethan b martin: 这个switch的写法很巧妙,不过不推荐。请不要鼓励开发者用这种方式去写js代码。我们曾经有一个工程师这么写,后来在代码review的时候,造成了很大的阅读苦难。好在我们及时将其重构为更加容易读懂的代码。不妨对比一下用swtich和if的区别:
function getwaterstate1(tempincelsius) { let state;  switch (true) {  case (tempincelsius <= 0):    state = 'solid';   break;  case (tempincelsius < 100):    state = 'liquid';   break;  default:    state = 'gas'; } return state;}function getwaterstate2(tempincelsius) { if (tempincelsius <= 0) {  return 'solid'; } if (tempincelsius < 100) {  return 'liquid'; } return 'gas';}
第二种写法有几点优势:
a) 代码量更少,更加易读;b) 你不需要声明一个局部变量,读者不会一直要去追踪你如何对这个变量做了更改;c) switch(true)真的会让人莫名其妙。
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
本地环境操作node服务器跨域用法总结
如何获取dom文档树内所有数据
以上就是很重要的9个使用技巧(附代码)的详细内容。
其它类似信息

推荐信息