js 技术

1、单行评级五角星代码:

var rate = 1;//rate的值取0~5 即可看到效果
console.log("★★★★★☆☆☆☆☆".slice(5-rate,10-rate));

2、输出sb

console.log((!(~+[])+{})[--[~+""][+[]]*[~+[]] + ~~!+[]]+({}+[])[[~!+[]]*~+[]]);//sb

3、输出nb

console.log(([][[]]+[])[+!![]]+([]+{})[!+[]+!![]]);  //nb

4、javascript错误处理方式

try{
   something
}catch(e){
   window.location.href="http://stackoverflow.com/search?q=[js]+"+e.message;
}

5、获取随机数

Math.random().toString(16).substring(2);
//或者
Math.random().toString(32).substring(2);

6、console.log((10)["toString"] === "10")  //true

7、金钱格式化 12345789 ->1,234,567,890

//正则表达式
var test1 = '1230001.24';
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g,',');
console.log(format)
8、最短的代码实现数组去重

console.log([...new Set([1,"1",2,1,1,3])]);

9、最短的代码实现一个长度是6且值都是8的数组

Array(6).fill(8);

10、获取一个数组中的最大值和最小值

var arr = [1,2,3,4,5,6,6];
var max = Math.max.apply(Math,arr);
var min = Math.min.apply(Math,arr);


默认参数值
为了给函数中参数传递默认值,通常使用if语句来编写,但是使用ES6定义默认值,则会很简洁:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}
简写:

volume = (l, w = 3, h = 4 ) => (l * w * h);
 
volume(2) //output: 24

19 个 JavaScript 有用的简写技术
javascript/jquery 浏览数:2602018-1-7
三元操作符
当想写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
短路求值简写方式
当给一个变量分配另一个值时,想确定源始值不是null,undefined或空值。可以写撰写一个多重条件的if语句。

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}
或者可以使用短路求值方法:

const variable2 = variable1 || 'new';
声明变量简写方法
let x;
let y;
let z = 3;
简写方法:

let x, y, z=3;
if存在条件简写方法
if (likeJavaScript === true)
简写:

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

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

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

let a;
if ( !a ) {
// do something...
}
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
短路评价
给一个变量分配的值是通过判断其值是否为null或undefined,则可以:

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = 'localhost';
}
简写:

const dbHost = process.env.DB_HOST || 'localhost';
十进制指数
当需要写数字带有很多零时(如10000000),可以采用指数(1e7)来代替这个数字:

for (let i = 0; i < 10000; i++) {}
简写:

for (let i = 0; i < 1e7; i++) {}
 
// 下面都是返回true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
对象属性简写
如果属性名与key名相同,则可以采用ES6的方法:

const obj = { x:x, y:y };
简写:

const obj = { x, y };
箭头函数简写
传统函数编写方法很容易让人理解和编写,但是当嵌套在另一个函数中,则这些优势就荡然无存。

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

sayHello = name => console.log('Hello', name);
 
setTimeout(() => console.log('Loaded'), 2000);
 
list.forEach(item => console.log(item));
隐式返回值简写
经常使用return语句来返回函数最终结果,一个单独语句的箭头函数能隐式返回其值(函数必须省略{}为了省略return关键字)

为返回多行语句(例如对象字面表达式),则需要使用()包围函数体。

function calcCircumference(diameter) {
  return Math.PI * diameter
}
 
var func = function func() {
  return { foo: 1 };
};
简写:

calcCircumference = diameter => (
  Math.PI * diameter;
)
 
var func = () => ({ foo: 1 });
默认参数值
为了给函数中参数传递默认值,通常使用if语句来编写,但是使用ES6定义默认值,则会很简洁:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}
简写:

volume = (l, w = 3, h = 4 ) => (l * w * h);
 
volume(2) //output: 24
模板字符串
传统的JavaScript语言,输出模板通常是这样写的。

const welcome = 'You have logged in as ' + first + ' ' + last + '.'
 
const db = 'http://' + host + ':' + port + '/' + database;
ES6可以使用反引号和${}简写:

const welcome = `You have logged in as ${first} ${last}`;
 
const db = `http://${host}:${port}/${database}`;
解构赋值简写方法
在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;
也可以分配变量名:

const { store, form, loading, errors, entity:contact } = this.props;
//最后一个变量名为contact
多行字符串简写
需要输出多行字符串,需要使用+来拼接:

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'
使用反引号,则可以达到简写作用:

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.`





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值