专业编程基础技术教程

网站首页 > 基础教程 正文

JavaScript 如何书写更优雅(javascript的书写位置有几种)

ccvgpt 2024-07-23 01:17:55 基础教程 11 ℃


平时在写代码逻辑时,有些代码会很长,如何更简洁的书写,让我们的代码更优雅:

JavaScript 如何书写更优雅(javascript的书写位置有几种)

1、三目运算

当想写 if...else 语句时,使用三目运算来代替。

var age = 20;

var tip;

if(age>18) {

tip ='你成年啦'

}else {

tip = '未成年喽'

}

简写:

var tip = age>18 ? '你成年啦' : '未成年喽';

2、声明变量简写方法

var a = 1;

var b = 2;

var c = 3;

简写方法:

var a = 1, var b = 2, var c = 3;

if存在条件简写方法

if (flag === true)

简写:

if (flag)

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

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

if (flag !== true)

简写:

if (!flag)

3.函数参数

给一个变量分配的值是通过判断其值是否为null或undefined,则可以:

function action(num) {

var a;

if(num) {

a = num;

} else {

a = 10;

}

}

简写:

function action(num) {

var a = num || 10;

}

4.箭头函数

箭头函数相当于匿名函数,并且简化了函数定义

var f = function(v){

return v;

};

f(2);

简写:

var f = v =>v; // 变量名 = 参数 = 函数体

5.模板字符串

传统的JavaScript语言,输出模板通常是这样写的。

$.each(data,function(index,item){ //index 索引 item 当前元素

$(".index-main ul").append('<li class="lists">'+

'<img src="'+item.product_img_url+'" width="150" height="150">'+

'<label>'+

'<b class="discount">'+item.product_uprice+'</b>'+

'<span class="price-text">'+item.product_price+'</span> '+

'</label> '+

'</li>')

});

ES6简写:

$.each(data,function(index,item){ //index 索引 item 当前元素

$(".index-main ul").append(`<li class="lists">

<img src="${item.product_img_url}" width="150" height="150">

<label>

<b class="discount">${item.product_uprice}</b>

<span class="price-text">${item.product_price}</span>

</label>

</li> `)

});

6.解构赋值简写方法

在web框架中,经常需要从组件和API之间来回传递数组或对象字面形式的数据,然后需要解构它。

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;

简写:

import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;

7.扩展运算符简写

扩展运算符有几种用例让JavaScript代码更加有效使用,可以用来代替某个数组函数。

数组合并 concat concat() 方法用于连接两个或多个数组。该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本。

var arr1=['a','b','c','d'];

var arr2=['e','f'];

var arr1=arr1.concat(arr2);

简写:

ES6 扩展运算符 它用于把一个数组转化为用逗号分隔的参数序列,它常用在不定参数个数时的函数调用

var arr3 = [0, 1, 2];

var arr4 = [4];

var arr3 = [...arr3, ...arr4];

感谢大家的支持,小编给粉丝们准备了书籍资料哦。麻烦转发+关注。私信我“资料".

Tags:

最近发表
标签列表