# 7个条件判断简化技巧

## 1. 多条件检查

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}


## 2. 简化 if true...else

// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;
console.log(test);


let x = 300,
test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"


## 3. if 判断值是否存在

// Longhand
if (test1 === true)
// or
if (test1 !== "")
// or
if (test1 !== null)
// Shorthand //it will check empty string,null and undefined too
if (test1)


## 4. 用于多个条件判断的 && 操作符

//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();


## 5. 比较后返回

// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}
// Shorthand
function checkReturn() {
return test || callMe('test');
}


## 6. switch 简化

// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[something] && data[something]();


## 7. 条件查找简化

// Longhand
if (type === 'test1') {
test1();
}
else if (type === 'test2') {
test2();
}
else if (type === 'test3') {
test3();
}
else if (type === 'test4') {
test4();
} else {
throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type);
func();


# 空值检查

## 使用操作符 ||

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
let test2 = test1;
}
// Shorthand
let test2 = test1 || '';


## 使用操作符 ??

const test= null ?? 'default';
console.log(test);
// expected output: "default"
const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0


# 6个声明变量、变量赋值技巧

## 1. 声明变量

//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1, test2 = 1;


## 2. 给多个变量赋值

//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];


## 3. 简便的赋值操作符

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;


## 4. 对象属性赋值

let test1 = 'a';
let test2 = 'b';
//Longhand
let obj = {test1: test1, test2: test2};
//Shorthand
let obj = {test1, test2};


## 5. 解构赋值

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;


## 6. 在没有第三个变量的情况下交换两个变量

let x = 1;
let y = 2;
// LONGER FORMlet
temp = x;
x = y;
y = temp;
// SHORTHAND
[x, y] = [y, x];


# 7个JavaScript字符串方法

## 1. slice() 方法

slice() 方法是一个字符串方法，它允许我们复制和提取部分字符串。

• 起始索引（要从其开始的字符索引）。
• 结束索引（要结束的字符的索引）。

const str = "JavaScript is Awesome";
str.slice(0, 10); //returns "JavaScript"


const str = "JavaScript is Awesome";
str.slice(14); //returns "Awesome"
str.slice(-7); //returns "Awesome"


## 2. concat()方法

concat() 方法允许将字符串连接和组合在一起。这就像使用一元运算符 + 进行字符串连接。

const tool = "JavaScript";
tool.concat(" is Awesome."); //returns "JavaScript is Awesome."
tool.concat(" Hello", " World"); //returns "JavaScript Hello World"


## 3. split() 方法

JavaScript 中的 split() 方法允许我们将字符串拆分为数组。 它使我们能够在 JavaScript 中将字符串转换为数组。

const str = "JavaScript is Awesome";
//convert to an array of single characters.
str.split("");
// returns ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t", " ", "i", "s", " ", "A", "w", "e", "s", "o", "m", "e"]
//convert to an array of words.
str.split(" "); //returns ["JavaScript", "is", "Awesome"]
//get the first two words inside an array.
str.split(" ", 2); //returns ["JavaScript", "is"]


## 4. includes() 方法

includes() 方法检查字符串是否包含作为方法参数传递的另一个特定字符串。 如果是，则返回 true 。 否则，它返回 false 。

const str = "JavaScript is Awesome";
str.includes("JavaScript"); //returns true
str.includes("Python"); //returns false


## 5. charCodeAt() 方法

charCodeAt()方法返回字符串中指定字符的 Unicode 编号。

const str = "JavaScript is Awesome";
str.charCodeAt(0); //returns 74
str.charCodeAt(2); //returns 118


## 6. fromCharCode()方法

fromCharCode() 方法允许我们将 Unicode 值转换为人类可以阅读的可读字符。 由于此方法是 String 对象的一部分，我们使用关键字 String 访问它。

String.fromCharCode(77); //returns "M"
String.fromCharCode(65); //returns "A"
String.fromCharCode(74, 65, 118, 65); //returns "JAVA"


## 7. replaceAll()方法

replaceAll() 方法是 ES2020 的新方法。 它允许我们将参数传递的另一个特定字符串替换一个字符串的多个实例。

replaceAll()方法接受两个参数：

• 要替换的字符串的实例。
• 将替换实例的字符串（你也可以传递普通字符串或函数）。

const str = "Hello Hello JavaScript";
str.replaceAll(/Hello/g, "Hi"); //returns "Hi Hi JavaScript"
str.replaceAll("Hello", "Hi"); //returns "Hi Hi JavaScript"
str.replaceAll("Hello", (i) => i + " World");
//returns "Hello World Hello World JavaScript"


# 数组操作技巧

## 1. 数组 find 简化

const data = [{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
]
function findtest1(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'test1' && data[i].name === name) {
return data[i];
}
}
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }


## 2. 快速调整大小和清空数组

const array = [1,2,3,4,5];
console.log（array）; // 5
array.length--;
console.log（array）; // 4
array.length + = 15;
console.log（array）; // 19


[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3, 4, ..15 empty]
undefined


let arr= ['a', 'b', 'c'];
arr.length = 0;
console.log(arr.length); // Ouput=> 0
console.log(arr); // Output=> []


## 3. 查找数组的最大值和最小值

const arr = [1, 2, 3];
Math.max(…arr); // 3
Math.min(…arr); // 1


## 4. 从数组中删除重复项

const nums = [1,1,1,1,3,4,5]
const uniqueNums = [...new Set(nums)];


const nums = [1,1,1,1,3,4,5]
const uniqueNums = Array.from(new Set(nums))


## 5. 转换为数组

const convertToArray = val => (Array.isArray(val) ? val : [val]);
convertToArray("Pro") // [Pro]
convertToArray(101) // [101]


# 17个JavaScript 数组方法

## 1、 Array.find()

const cars = [
{brand: "Porsche", price: 105000},
{brand: "BMW", price: 32000},
{brand: "Skoda", price: 15000},
{brand: "Toyota", price: 11500}
];
const affordableCar = cars.find(car => car.price <= 20000);
console.log(affordableCar)


{
brand:"Skoda",
price:15000
}


## 2、Array.concat()

const nums1 = [1,2,3];
const nums2 = [4,5,6];
const merged = nums1.concat(nums2);
console.log(merged);


## 3、 Array.findIndex（）

const nums = [1,2,3,3,3,2,1]
const idx = nums.findIndex( num => num == 3 )
console.log(idx)


2


## 4、Array.forEach()

const nums = [1, 2, 3];
nums.forEach( num => console.log(num) );


1
2
3


## 5、 Array.join()

const words = ["This", "is", "a test"];
const sentence = words.join(" "); // separate words by blank spaces
console.log(sentence)


This is a test


## 6、 Array.map（）

const nums = [1,2,3,4,5];
const squaredNums = nums.map( number => number * number );
console.log(squaredNums);


[1, 4, 9, 16, 25]


## 7、Array.reduce()

const nums = [1,2,3,4,5,6];
const numSum = nums.reduce((sum, num) => sum + num);
console.log(numSum);


21


• 第一个值是累积的“总”值。在这种情况下，它被称为sum。随着该.reduce()方法通过数字工作，该值逐渐增加。
• 第二个值是 reduce 操作的当前元素。在这种情况下，它被称为num。
• 简而言之，所有.reduce()要做的就是遍历数组的每个元素，并将每个值添加到 中sum以获得数字的总和。

const nums = [1,2,3,4,5,6];
const numSum = nums.reduce((sum, num) => sum + num, 1000);
console.log(numSum);


1021


## 8、 Array.flat()

const nums = [0，1，2，[3，4]];
console.log(nums.flat());


[0, 1, 2, 3, 4]


const nums = [0, 1, 2, [[[[[3, 4]]]]]];
console.log(nums.flat(2));


[0，1，2，[3，4]]


## 9、Array.push()

let nums = [1, 2, 3]
nums.push(4)
nums.push(5, 6)
console.log(nums)


[1, 2, 3, 4, 5, 6]


## 10、 Array.pop()

let nums = [1, 2, 3, 4, 5, 6]
const lastNum = nums.pop()
console.log(Removed ${lastNum}, now the numbers are${nums})


Removed 6, now the numbers are 1,2,3,4,5


## 11、 Array.shift()

const nums = [1, 2, 3, 4];
const first = nums.shift();

console.log(nums);
console.log(first);


[2, 3, 4]
1


## 12、 Array.unshift（）

const nums = [1, 2, 3];
nums.unshift(4, 5);
console.log(nums);


[4, 5, 1, 2, 3]


## 13、 Array.filter()

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNums = nums.filter( num => num % 2 == 0);
console.log(evenNums);


[2, 4, 6, 8, 10]


## 14、 Array.sort()

const fruits = ["Banana", "Apple", "Clementine"]
const sorted = fruits.sort()
console.log(sorted)


["Apple", "Banana", "Clementine"]


const nums = [1, 2, 3, 4]
const sorted = nums.sort((a, b) => a - b)
console.log(sorted)


## 15、 Array.reverse()

const nums = [1, 2, 3, 4]
const reversed = nums.reverse()
console.log(reversed)


[4, 3, 2, 1]


## 16、Array.every()

const moods = ["hungry", "hungry", "hungry"];
const allHungry = moods.every(mood => mood === "hungry");
console.log(allHungry);


true


## 17、Array.some()

const moods = ["hungry", "sleepy", "thirsty"];
const someHungry = moods.some(mood => mood === "hungry");

console.log(someHungry);


true


# 4个JavaScript中的？操作符

## 1. ?? 操作符

null ?? 5 // => 5
3 ?? 5 // => 3


var prevMoney = 1
var currMoney = 0
var noAccount = null
var futureMoney = -1

function moneyAmount(money) {
return money || You currently do not own an account in the bank
}

console.log(moneyAmount(prevMoney)) // => 1
console.log(moneyAmount(currMoney)) // => You currently do not own an account in the bank
console.log(moneyAmount(noAccount)) // => You currently do not own an account in the bank
console.log(moneyAmount(futureMoney))//  => -1


var currMoney = 0
var noAccount = null

function moneyAmount(money) {
return money ?? You currently do not own an account in the bank
}
moneyAmount(currMoney) // => 0
moneyAmount(noAccount) // => You currently do not own an account in the bank


## 2. ??= 操作符

??= 又称为逻辑 nullish 赋值操作符，与我们之前学到的内容密切相关。让我们看看它们是如何联系在一起的。

var x = null
var y = 5

console.log(x ??= y) // => 5
console.log(x = (x ?? y)) // => 5


function gameSettingsWithNullish(options) {
options.gameSpeed ??= 1
options.gameDiff ??= 'easy'
return options
}

function gameSettingsWithDefaultParams(gameSpeed=1, gameDiff='easy') {
return {gameSpeed, gameDiff}
}

gameSettingsWithNullish({gameSpeed: null, gameDiff: null}) // => { gameSpeed: 1, gameDiff: 'easy' }
gameSettingsWithDefaultParams(null, null) // => { gameSpeed: null, gameDiff: null }


## 3. ?. 操作符

var travelPlans  = {
destination: 'DC',
monday: {
location: 'National Mall',
budget: 200
}
};

const tuesdayPlans = travelPlans.tuesday?.location;
console.log(tuesdayPlans) // => undefined


function addPlansWhenUndefined(plans, location, budget) {
if (plans.tuesday?.location === undefined) {
var newPlans = {
plans,
tuesday: { location: location ?? "Park", budget: budget ?? 200 },
};
} else {
newPlans ??= plans; //will only override if newPlans is undefined
}
return newPlans;
}

var newPlans = addPlansWhenUndefined(travelPlans, "Ford Theatre", null);
console.log(newPlans) // => { plans:
//{ destination: 'DC',
// monday: { location: 'National Mall', budget: 200 } },
// tuesday: { location: 'Ford Theatre', budget: 200 } }

newPlans = addPlansWhenUndefined(newPlans, null, null) // logs => Plans have already been added!
// returns => newPlans object


## 4. ? 操作符

function checkCharge(charge) {
return (charge > 0) ? 'Ready for use' : 'Needs to charge'
}

console.log(checkCharge(20)) // => 'Ready for use'
console.log(checkCharge(0)) // => 'Needs to charge'


var budget = 0
var transportion = (budget > 0) ? 'Train' : 'Walking'
console.log(transportion) // => 'Walking'


var x = 6
var x = (x !== null || x !== undefined) ? x : 3
console.log(x) // => 6


function nullishAssignment(x,y) {
return (x == null || x == undefined) ? y : x
}

var x = nullishAssignment(null, 8) // => 8
var y = nullishAssignment(4,8) // => 4


function addPlansWhenUndefined(plans, location, budget) {
var newPlans =
plans.tuesday?.location === undefined
? {
...plans,
tuesday: { location: location ?? "Park", budget: budget ?? 200 },
}
newPlans ??= plans;
return newPlans;
}


# 6个JavaScript对象操作方法

## 1. Object.entries()

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/


## 2. Object.values()

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/


## 3. Object.keys()

let cat = {
name: 'Jimmy boy',
age: 5,
breed: 'British Shorthair',
favorite_word: 'Meow',
favorite_food: 'Chimkens'
}

console.log(Object.keys(cat)); // [ 'name', 'age', 'breed', 'favorite_word', 'favorite_food' ]


Object.keys 返回一个数组，我们可以迭代它并使用这些键做任何我们需要做的事情。

## 4. Object.freeze( )

const employee = {
name: "James",
age: 25,
available: true
}
//Freezing the object.
Object.freeze(employee);
//updating and adding properties.
employee.newProp = "Hard Worker";
console.log(employee);
//Output: {name: "James", age: 25, available: true}


## 5. Object.seal( )

const user = {
name: "Alex",
age: 23,
isOnline: false
}
//使用Object.seal（）
Object.seal(user);
//更新属性。
user.isOnline = true;
//添加一个属性。
user.active = false;
console.log(user);
//输出：{名称：“ Alex”，年龄：23，isOnline：true}


## 6. Object.create( )

const user = {
firstName: "John",
lastName: "Doe",
age: 25,
fullName(){
return ${this.firstName}${this.lastName};
}
}
//新对象。
let newObject = Object.create(user);
//更新属性。
newObject.firstName = "Mehdi";
//我们也可以在此新对象中使用user的fullName方法。
console.log(newObject);


# 函数相关

## 箭头函数

//Longhand
function add(a, b) {
return a + b;
}
//Shorthand
const add = (a, b) => a + b;


function callMe(name) {
console.log('Hello', name);
}
callMe = name => console.log('Hello', name);


## 隐式返回

//longhand
function calculate(diameter) {
return Math.PI * diameter
}
//shorthand
calculate = diameter => (
Math.PI * diameter;
)


## 简短的函数调用

// Longhand
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}
// Shorthand
(test3 === 1? test1:test2)();


# for循环

// 一个这个大的数组
var array = []
array.length = 10000000

var array = []
array.length = 10000000

console.time('for++')
for (let i = 0; i < array.length; i++) {

}
console.timeEnd('for++') // 7.009033203125 ms

console.time('for--')
for (let i = array.length; i > 0; i--) {

}
console.timeEnd('for--') // 6.798828125 ms

console.time('forEach')
array.forEach(function () {

})

console.timeEnd('forEach') // 25.0791015625 ms

console.time('forOf')
for (let i of array) {

}

console.timeEnd('forOf') // 174.65478515625 ms


## 正序常规for循环

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

}


## 倒叙常规for循环

for (let i = array.length; i > 0; i--) {

}


## forEach

array.forEach(function () {

})


## for ... of ...

for...of是在ES6（ECMAScript中6）中实现标准化的。它会基于一个可迭代对象，比如array，map，set，string等创建一个循环，并且拥有更优秀的可读性。

for (const i of array) {

}


## for ... in...

for (const i in array) {

}


for..of和for...in之间的主要区别是它们迭代的内容。上面所说的for...in环路迭代的是对象的属性，而for...of循环遍历一个迭代对象的值。

# 其他

## 指数表示法

// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {


## 默认参数值

//Longhand
function add(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);


## 模板字面量

//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = Hi ${test1}${test2};


## 跨行字符串

//longhand
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t'
//shorthand
const data = abc abc abc abc abc abc
test test,test test test test


## 将字符串转成数字

//Longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
//Shorthand
let test1 = +'123';
let test2 = +'12.3';


## indexOf 的按位操作简化

//longhand
if(arr.indexOf(item) > -1) { // item found
}
if(arr.indexOf(item) === -1) { // item not found
}
//shorthand
if(~arr.indexOf(item)) { // item found
}
}


if (arr.includes(item)) {
// true if the item found
}


## 双重按位操作/Math.floor() 简写

// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true


## 重复字符串多次

//longhand
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test
//shorthand
'test '.repeat(5);


## 获取字符串的字符

let str = 'abc';
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c


## 指数幂简化/ Math.pow() 简写

//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8


## 将任何值转换为布尔值


!!true    // true
!!2       // true
!![]      // true
!!"Test"  // true

!!false   // false
!!0       // false
!!""      // false


## 字节大小

const byteSize1 = str => new Blob([str]).size;
const byteSize2 = int => new Blob([int]).size;
byteSize1("JavaScript") // 10
byteSize2(101) // 3


## 大写

const capitalize = str =>
str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalize('code'); //Code
capitalize('javascript programming'); //Javascript Programming


## 数字化


const digitize = n => [...\${n}].map(i => parseInt(i));
digitize(345) // [3,4,5]
digitize(123) // [1,2,3]
digitize(6) // [6]


## isUpper Case

const isUpperCase = str => str === str.toUpperCase();
isUpperCase("Code") //false
isUpperCase("PROGRAMMING") //true
isUpperCase("aB") //false


## isLower Case

const isLowerCase = str => str === str.toLowerCase();
isLowerCase("code") //true
isLowerCase("PROGRAMMING") //false


## 范围生成器中的整数数组

const randomIntArrayInRange = (min, max, n = 1) =>
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
console.log(randomIntArrayInRange(10, 15, 5)); // [ 14, 11, 15, 10, 13 ]


## 范围生成器中的随机整数

const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInteger(1,10)) // 6
console.log(randomInteger(1,20)) // 8


## 从列表中删除 False 元素

const compactJs = arr => arr.filter(Boolean);
compactJs([2,4,false,NaN,5,"",0]) //[2,4,5]

posted @ 2021-08-25 15:16  CherishTheYouth  阅读(192)  评论(1编辑  收藏  举报