首页 > 语言 > JavaScript > 正文

分享19个JavaScript 有用的简写写法

2024-05-06 15:14:45
字体:
来源:转载
供稿:网友

原文链接,最近很火的一篇文章

This really is a must read for any JavaScript-based developer. I have written this article as a vital source of reference for learning shorthand JavaScript coding techniques that I have picked up over the years. To help you understand what is going on I have included the longhand versions to give some coding perspective.

这篇文章对于任何基于javascript开发人员是必须要看的文章了,我写这篇文章是学习多年来我所熟悉的JavaScript 简写方法,为帮助大家学习理解特整理了一些非简写的写法。

June 14th, 2017: This article was updated to add new shorthand tips based on ES6. If you want to learn more about the changes in ES6, sign up for SitePoint Premium and check out our screencast A Look into ES6

本文来源于多年的 JavaScript 编码技术经验,适合所有正在使用 JavaScript 编程的开发人员阅读。

本文的目的在于帮助大家更加熟练的运用 JavaScript 语言来进行开发工作。

文章将分成初级篇和高级篇两部分,分别进行介绍。

1.三元操作符

当想写if...else语句时,使用三元操作符来代替。

普通写法:

const x = 20;let answer;if (x > 10) { answer = 'is greater';} else { answer = 'is lesser';}

简写:

const answer = x > 10 ? 'is greater' : 'is lesser';

也可以嵌套if语句:

const big = x > 10 ? " greater 10" : x

2.短路求值简写方式

当给一个变量分配另一个值时,想确定源始值不是nullundefined或空值。可以写撰写一个多重条件的if语句。

if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1;}

或者可以使用短路求值方法:

const variable2 = variable1 || 'new';

3.声明变量简写方法

let x;let y;let z = 3;

简写方法:

let x, y, z=3;

4.if存在条件简写方法

if (likeJavaScript === true)

简写:

if (likeJavaScript)

只有likeJavaScript是真值时,二者语句才相等

如果判断值不是真值,则可以这样:

let a;if ( a !== true ) {// do something...}

简写:

let a;if ( !a ) {// do something...}

5.JavaScript循环简写方法

for (let i = 0; i < allImgs.length; i++)

简写:

for (let index in allImgs)

也可以使用Array.forEach

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            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选