扣丁学堂HTML5培训分享值得学习的JavaScript编码小技巧

ITxuexi_66 · · 1404 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

本篇文章扣丁学堂HTML5培训小编给读者们分享一下值得学习的JavaScript编码小技巧,对JavaScript感兴趣的小伙伴就随小编来了解一下吧,希望对小伙伴们有所帮助。 隐式返回 return在函数中经常使用到的一个关键词,将返回函数的最终结果。箭头函数用一个语句将隐式的返回结果(函数必须省略{},为了省略return关键词)。 如果返回一个多行语句(比如对象),有必要在函数体内使用()替代{}。这样可以确保代码是否作为一个单独的语句返回。 Longhand: function calcCircumference(diameter) { return Math.PI * diameter } Shorthand: calcCircumference = diameter => ( Math.PI * diameter; ) 默认参数值 你可以使用if语句来定义函数参数的默认值。在ES6中,可以在函数声明中定义默认值。 Longhand: function volume(l, w, h) { if (w === undefined) w = 3; if (h === undefined) h = 4; return l * w * h; } Shorthand: volume = (l, w = 3, h = 4 ) => (l * w * h); volume(2) //output: 24 Template Literals 是不是厌倦了使用+来连接多个变量变成一个字符串?难道就没有一个更容易的方法吗?如果你能使用ES6,那么你是幸运的。在ES6中,你要做的是使用撇号和${},并且把你的变量放在大括号内。 Longhand: const welcome = 'You have logged in as ' + first + ' ' + last + '.' const db = 'http://' + host + ':' + port + '/' + database; Shorthand: const welcome = `You have logged in as ${first} ${last}`; const db = `http://${host}:${port}/${database}`; Destructuring Assignment 如果你正在使用任何一个流行的Web框架时,就有很多机会使用数组的形式或数据对象的形式与API之间传递信息。一旦数据对象达到一个对个组件时,你需要将其展开。 Longhand: const observable = require('mobx/observable'); const action = require('mobx/action'); const runInAction = require('mobx/runInAction'); const store = this.props.store; const form = this.props.form; const loading = this.props.loading; const errors = this.props.errors; const entity = this.props.entity; Shorthand: import { observable, action, runInAction } from 'mobx'; const { store, form, loading, errors, entity } = this.props; 你甚至可以自己指定变量名: const { store, form, loading, errors, entity:contact } = this.props; 多行字符串 你会发现以前自己写多行字符串的代码会像下面这样: Longhand: const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t' + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t' + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t' + 'veniam, quis nostrud exercitation ullamco laboris\n\t' + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t' + 'irure dolor in reprehenderit in voluptate velit esse.\n\t' 但还有一个更简单的方法。使用撇号。 Shorthand: const lorem = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.` Spread Operator Spread Operator是ES6中引入的,使JavaScript代码更高效和有趣。它可以用来代替某些数组的功能。Spread Operator只是一个系列的三个点(...)。 Longhand: // joining arrays const odd = [1, 3, 5]; const nums = [2 ,4 , 6].concat(odd); // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = arr.slice() Shorthand: // joining arrays const odd = [1, 3, 5 ]; const nums = [2 ,4 , 6, ...odd]; console.log(nums); // [ 2, 4, 6, 1, 3, 5 ] // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = [...arr]; 不像concat()函数,使用Spread Operator你可以将一个数组插入到另一个数组的任何地方。 const odd = [1, 3, 5 ]; const nums = [2, ...odd, 4 , 6]; 另外还可以当作解构符: const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 }; console.log(a) // 1 console.log(b) // 2 console.log(z) // { c: 3, d: 4 } 强制参数 默认情况下,JavaScript如果不给函数参数传一个值的话,将会是一个undefined。有些语言也将抛出一个警告或错误。在执行参数赋值时,你可以使用if语句,如果未定义将会抛出一个错误,或者你可以使用强制参数(Mandatory parameter)。 Longhand: function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; } Shorthand: mandatory = () => { throw new Error('Missing parameter!'); } foo = (bar = mandatory()) => { return bar; } Array.find 如果你以前写过一个查找函数,你可能会使用一个for循环。在ES6中,你可以使用数组的一个新功能find()。 Longhand: const pets = [ { type: 'Dog', name: 'Max'}, { type: 'Cat', name: 'Karl'}, { type: 'Dog', name: 'Tommy'}, ] function findDog(name) { for(let i = 0; i<pets.length; ++i) { if(pets[i].type === 'Dog' && pets[i].name === name) { return pets[i]; } } } Shorthand: pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy'); console.log(pet); // { type: 'Dog', name: 'Tommy' } Object[key] 你知道Foo.bar也可以写成Foo[bar]吧。起初,似乎没有理由应该这样写。然而,这个符号可以让你编写可重用代码块。 下面是一段简化后的函数的例子: function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // true 这个函数可以正常工作。然而,需要考虑一个这样的场景:有很多种形式需要应用验证,而且不同领域有不同规则。在运行时很难创建一个通用的验证功能。 Shorthand: // object validation rules const schema = { first: { required:true }, last: { required:true } } // universal validation function const validate = (schema, values) => { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true; } console.log(validate(schema, {first:'Bruce'})); // false console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true 现在我们有一个验证函数,可以各种形式的重用,而不需要为每个不同的功能定制一个验证函数。 Double Bitwise NOT 如果你是一位JavaScript新手的话,对于逐位运算符(Bitwise Operator)你应该永远不会在任何地方使用。此外,如果你不处理二进制0和1,那就更不会想使用。 然而,一个非常实用的用例,那就是双位操作符。你可以用它替代Math.floor()。Double Bitwise NOT运算符有很大的优势,它执行相同的操作要快得多。你可以在这里阅读更多关于位运算符相关的知识。 Longhand: Math.floor(4.9) === 4 //true Shorthand: ~~4.9 === 4 //true 想要了解更多关于HTML5方面内容的小伙伴,请关注扣丁学堂HTML5培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供权威的HTML5开发视频,HTML5培训后的前景无限,行业薪资和未来的发展会越来越好的,扣丁学堂老师精心推出的HTML5视频教程定能让你快速掌握HTML5从入门到精通开发实战技能。扣丁学堂H5技术交流群:673883249。

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1404 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传