<返回更多

17 个高频好用的JavaScript 代码块

2021-12-30    Mason程
加入收藏

JAVAScript 的故事很长。在今天,JavaScript 的运行从移动设备到服务器端,无论您是计划在 2022 年学习或使用 JavaScript ,还是目前正在使用JavaScript进行开发,还是已经熟练掌握了JavaScript技能,我在这里与您分享的这17个高频使用的JavaScript代码段,对您一定会有一些帮助。

好了,我们现在就开始吧。

1、短路表达式

const defaultSafeValue = "defaultSafeValue"
let someValueNotSureOfItsExistence = null
let expectingSomeValue = someValueNotSureOfItsExistence || defaultSafeValue
console.log(expectingSomeValue)

如果 someValueNotSureOfItsExistance 为 undefined/null/false,则 defaultSafeValue 将就位。

如果我们不确定任何值是否存在,这会很方便。它还确保您不会从错误的对象中查看任何内容,即如下所示。

let someValueNotSureOfItsExistence = null
// let someValueNotSureOfItsExistence = { expectingSomeValue:1 }
let { expectingSomeValue } = someValueNotSureOfItsExistence ||  {}
console.log(expectingSomeValue)

你可以在上面的代码中取消注释,看看它可以避免可能的崩溃。

2、IF条件

let someValue = true // or some value like 1,.. {} etc
if(someValue){
   console.log('Yes. Its exist')
}

3、多重条件

const conditions = ["Condition 2","Condition String2"];someFunction(str){
  if(str.includes("someValue1") || str.includes("someValue2")){
    return true
  }else{
    return false
  }
}

同样可以通过以下方式完成

someFunction(str){
   const conditions = ["someValue1","someValue2"];
   return conditions.some(condition=>str.includes(condition));
}

4、模板文字

let name = "John Doe", profession = "Engineering"
let someSentence = `My Name is ${name} and he is doing ${profession}`
console.log(someSentence)
// His Name is John Doe and he is doing Engineering

5、解构赋值

let personObject = {
  name:"John Doe",
  phone:"1234",
  address:{
    line:"abc ave",
    postCode:12223,
  },
}
const {name, phone, address} = personObject;

我们经常在像 React 这样的框架中这样做,如下所示

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

6、扩展运算符

const previousNumber = [1, 3, 5 ];
const allNumbers = [2 ,4 , 6, ...previousNumber];
console.log(allNumbers);
// [ 2, 4, 6, 1, 3, 5 ]
//Handy if you want to merge two objects

7、箭头功能简写

var sayHello = (name)=>{
   return "Hello " + name
}
console.log(sayHello("John"))

反而

var sayHello = (name)=> "Hello " + name
console.log(sayHello("John"))

8、条件函数调用

function fn1(){
  console.log('I am Function 1');
}
function fn2(){
  console.log('I am Function 2');
}
let checkValue = 3;
if(checkValue === 3){
 fn1();
}else{
 fn2();
}

相反,简而言之

(checkValue ===3 ? fn1:fn2)(); // Short Version

9、&& 运算符

var value = true; // or true or some value exist
if(value){
  console.log('Value is there or true')
}
// OR via this way
value && console.log('Value is there or true')

10、 将字符串转换为数字

const numberStr1 = "100";
const numberStr2 = "200";
var sampleValue = +numberStr1 + +numberStr2;
console.log(sampleValue);
console.log(typeof sampleValue); // Its a number!

11、避免过多的函数参数

function myFunction(employeeName,jobTitle,yrExp,majorExp){
}
// you can call it via
myFunction("John","Project Manager",12,"Project Management");
//    ***** PROBLEMS ARE *****
// Violation of ‘clean code’ principle
// Parameter sequencing is important
// Unused Params warning if not used 
// Testing need to consider a lot of edge cases.

相反,创建一个 params 对象,如

const mockTechPeople = {
employeeName:'John',
jobTitle:'Project Manager',
yrExp:12,
majorExp:'Project Management'
}

并在函数中解构 params 使其更清晰,产生错误的可能性更小。

function myFunction({employeeName,jobTitle,yrExp,majorExp}){


     // ES2015/ES6 destructuring syntax is in action
     // map your desired value to variable you need.
}

现在调用很简单

myFunction(mockTechPeople); // Only One argument

12、 默认参数值

function rectangle(h,w){
 if(!h){
   h=0;
 }else if(!w){
  w=0;
 }
 return h*w;
}
console.log(rectangle())

反而

function rectangle(h =0,w=0){
  return h*w;
}
console.log(rectangle(1,12))

13、Math.Floor 简写

var val = "1212121212"
console.log(Math.floor(val)) // Long one
console.log(~~val) // smart one

14、toString 简写

var someNumber = 123
console.log(someNumber.toString()) //return "123"
// Or in SHORT CUT
console.log(`${someNumber}`) //return "123"

15、For 循环

for(let i=0;i<1e3;i++){ // instead of i<1000, Cool, right?   
}

16、值到对象映射,即键和值相同

var x='x',y='y'
var obj = {x,y} // instead of {x:x, y:y}
console.log(obj)

17、多行字符串

var multiLineString = `some stringn
with multi-line ofn
charactersn`
console.log(multiLineString)
声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>