网络编程 
首页 > 网络编程 > 浏览文章

JavaScript编码小技巧分享

(编辑:jimmy 日期: 2024/5/8 浏览:3 次 )

三元操作符

如果使用if...else语句,那么这是一个很好节省代码的方式。

const x = 20;
let big;
if (x > 10) {
big = true;
} else {
big = false;
}
//这样写...
const big = x > 10 "htmlcode">
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
// 这样写
const variable2 = variable1 || 'new';

不要相信我,请先相信自己的测试(可以把下面的代码粘贴在es6console)

let variable1;
let variable2 = variable1 || '';
console.log(variable2 === ''); // true
variable1 = 'foo';
variable2 = variable1 || '';
console.log(variable2); // foo

声明变量

在函数中声明变量时,像下面这样同时声明多个变量可以节省你大量的时间和空间:

let x;
let y;
let x = 3;

// or 
"htmlcode">
if (likeJavaScript === true)
//or
if (likeJavaScript)"htmlcode">
let a;
if (a !== true) {
// do something ...
}
//or
let a;
if (!a) {
// do something ...
}"htmlcode">
for (let i = 0; i < allImgs.length; i++)
//or
for (let index in allImgs)"htmlcode">
function logArrayElements(element, index, array) {
console.log('a[' + index + ']=' + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

对象属性

定义对象文字(Object literals)让JavaScript变得更有趣。ES6提供了一个更简单的办法来分配对象的属性。如果属性名和值一样,你可以使用下面简写的方式。

const obj = {x: x, y: y};
//or
const obj = {x, y};

箭头函数

经典函数很容易读和写,但它们确实会变得有点冗长,特别是嵌套函数中调用其他函数时还会让你感到困惑。

function sayHello(name) {
console.log('Hello', name);
}
setTimeout(function() {
console.log('Loaded')
}, 2000);
list.forEach(function(item){
console.log(item)
})

//or
sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));"htmlcode">
function calcCircumference(diameter) {
return Math.PI * diameter
}
//or
calcCircumference = diameter => (
Math.PI * diameter;
)"htmlcode">
function volume(l, w, h) {
if (w === undefined)
    w = 3;
if (h === undefined)
    h = 4;
return l * w * h;
}
//or
volume = (l, w = 3, h = 4) => (l * w * h);
volume(2); // 24"htmlcode">
const welcome = 'You have logged in as' + first + ' ' + last + '.';
const db = 'http://' + host + ':' + port + '/' + database;
//or
const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;

Destructuring Assignment(解构赋值)

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;

//or

import {observable, action, runInAction} from 'mobx';
const {store, form, loading, errors, entity} = this.props;"htmlcode">
const {store, form, loading, errors, entity:contact} = this.props; //通过 : 号来重命名

Spread Operator(扩展运算符)

Spread Operator是ES6中引入的,使JavaScript代码更高效和有趣。它可以用来代替某些数组的功能。Spread Operator只是一个系列的三个点(...)。

// 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();
//or
// 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}

强制参数

function foo(bar) {
if (bar === undefined) {
throw new Error('Missing parameter!');
  }
return bar;
}
//or
mandatory = () => {
throw new Error('Missing parameter!');
}
foo = (bar = mandatory()) => {
return bar;
}

Array.find

如果你以前写过一个查找函数,你可能会使用一个for循环。在ES6中,你可以使用数组的一个新功能find()。

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];
    }
  }
}
 // or
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

这个函数可以正常工作。然而,需要考虑一个这样的场景:有很多种形式需要应用验证,而且不同领域有不同规则。在运行时很难创建一个通用的验证功能。

// 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运算符有很大的优势,它执行相同的操作要快得多。你可以在这里阅读更多关于位运算符相关的知识。

Math.floor(4.9) === 4; // true
//or
~~4.9 === 4; //true

以上就是JavaScript编码小技巧分享的详细内容,更多关于JavaScript编码技巧的资料请关注其它相关文章!

上一篇:详解JavaScript中的数据类型,以及检测数据类型的方法
下一篇:如何利用node转发请求详解