web代码片段

目录


1、变量

1.1、对象

let obje = {
    
    
	newArray: arrayData.map((item)=> item.id)
};

1.2、数组


2、函数

2.1、函数式编程

案例 1

var add = function (a, b) {
    
    
	return a + b;
};
var multiply = function (a, b) {
    
    
	return a * b;
};

var a = 5;
var b = 2;
var c = 0;

// ---
// 结合律(assosiative)
console.log(add(add(a, b), c) == add(a, add(b, c)));
// true

// 交换律(commutative)
console.log(add(a, b) == add(b, a));
// true

// 同一律(identity)
console.log(add(a, 0) == a);
// true

// 分配律(distributive)
console.log(multiply(a, add(b, c)) == add(multiply(a, b), multiply(a, c)));
// true

// ---
// 原有代码
console.log(add(multiply(b, add(a, c)), multiply(a, b)));
// 20

// 应用同一律,去掉多余的加法操作 -- add(a, c) == a
console.log(add(multiply(b, a), multiply(a, b)));
// 20

// 再应用分配律
console.log(multiply(b, add(a, a)));
// 20

案例 2

// 暂无

2.2、一等公民的函数

案例 1

const hi = (name) => `Hi ${
      
      name}`;
const greeting = (name) => hi(name);
console.log(greeting('parameter'));
// Hi parameter

console.log(hi);
// ƒ hi(name) { return "Hi ".concat(name); }

console.log(hi('jonas'));
// Hi jonas

案例 2

const BlogController = {
    
    
	index(posts) {
    
    
		return Views.index(posts);
	},
	show(post) {
    
    
		return Views.show(post);
	},
	create(attrs) {
    
    
		return Db.create(attrs);
	},
	update(post, attrs) {
    
    
		return Db.update(post, attrs);
	},
	destroy(post) {
    
    
		return Db.destroy(post);
	},
};

// 简化后的代码
const BlogControllerSimplify = {
    
    
	index: Views.index,
	show: Views.show,
	create: Db.create,
	update: Db.update,
	destroy: Db.destroy,
};

3、字符串

案例 1

function cuttingString(data, i) {
    
    
	let splitOne = data.split(' ');
	let splitTwo = splitOne[i].split(',');
	return {
    
    
		splitOne,
		splitTwo: splitTwo.map((item) => Number(item)),
	};
}
console.log(cuttingString('00 00 00 1,18,19,17,10,8,25,21 * ? *', 3));
// {splitOne: Array(7), splitTwo: Array(8)}
// splitOne: ["00", "00", "00", "1,18,19,17,10,8,25,21", "*", "?", "*"]
// splitTwo: [1, 18, 19, 17, 10, 8, 25, 21]

4、32个有用的JS 代码片段,让你的代码显得更专业

大千世界出品


4.1、字节大小

显示字符串或整数的字节大小。简单来说,它会显示字符串或整数的长度。

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

4.2、转换为数组

这个代码片段方法会将非数组值或数据转换为数组形式。

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

4.3、首字母转大写

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

4.4、获取当前网址

此代码段将有助于获取运行 javascript 的当前 URL。这在前端调试中派上用场。

const currentURL = () => window.location.href;
console.log(currentURL()); // https://medium.com/@codedev101

4.5、数字转数组

它会将数字转换为数字数组。

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

4.6、计数出现次数

此片段代码将计算数组中某个值的出现次数。当想知道一个值在大尺寸数组中出现多少次时,这会派上用场。

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
console.log(countOccurrences([2,4,6,2,5,2], 2)); // 3 
console.log(countOccurrences([1,4,6,2,5,6], 6)); // 2

4.7、字谜

此片段代码用于检查特定字符串是否为字谜。字谜是可以改写成另一个词的词。

const Anagram = (string1, string2) => {
    
    
	const normalize = str => str.toLowerCase().replace(/[^a-z0-9]/gi, '').split('').sort().join('');
	return normalize(string1) === normalize(string2);
};
console.log(Anagram("race", "care")); // true
console.log(Anagram("part", "trap")); // true

4.8、检查浏览器标签焦点

此片段代码将告诉你当前运行 javaScript 的浏览器选项卡是否处于焦点状态。

const Browser_Tab_Focused = () => !document.hidden;
console.log(Browser_Tab_Focused()); // true

4.9、检查浏览器

这段代码会告诉你运行 JavaScript 的环境是浏览器还是非浏览器。众所周知,我们可以在浏览器中运行 JavaScript,node js如果我们可以检查我们在哪个环境中工作,那就太好了。

const isBrowser = () => ![typeof window, typeof document].includes('undefined');
console.log(isBrowser()); // true   if on isBrowser
console.log(isBrowser()); // false  if we are on node js or any other environment

4.10、isNull

这段代码将检查变量或值是否为空。

const checkNull = val => val === undefined || val === null;
console.log(checkNull()); // true
console.log(checkNull(234)); // false

4.11、isNumber

这个简单的片段代码将检查值的变量是否为数字。

function isNumeric(num) {
    
     
	return !isNaN(parseFloat(num)) && isFinite(num); 
}
console.log(isNumeric(324)); // true 
console.log(isNumeric("Code")); // false

4.12、isString

此片段代码将检查变量或值是否为字符串。

const isString = val => typeof val === 'string';
console.log(isString('hello world')); // true
console.log(isString('1234')); // true
console.log(isString(345)); // false

4.13、最大数字

此代码段方法将返回列表中的最大数字。这是从列表中找到最大数字的最快方法。

const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
console.log(maxN([3,8,7])); // 8 
console.log(maxN([1,5,6,23])); // 23

4.14、最小数字

这段代码将快速返回列表中最小的数字。

const minimum = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
console.log(minimum([2,4,6,1]));   // 1
console.log(minimum([22, 55, 66, 77, 11, 19]));  // 11

4.15、反转

此片段代码只是反转字符串。这在你需要反转字符串或检查回文的简短任务中派上用场。

const reverseStr = str => [...str].reverse().join('');
console.log(reverseStr("JavaScript")); // tpircSavaJ 
console.log(reverseStr("123")); // 321

4.16、从列表中随机

此片段代码用于从列表中选择随机数。

const random = arr => arr[Math.floor(Math.random() * arr.length)];
console.log(random([1,4,5,6])); // 6 
console.log(random([1,4,0,6])); // 1

4.17、列表的头部元素

这段代码将展示如何快速获取任何列表的第一个元素。

const head = arr => arr[0];
console.log(head([1,2,3])); // 1 
console.log(head(["JavaScript", "Python", "C++"])); // JavaScript

4.18、列表的尾部元素

这段代码将展示如何以简单快捷的方式获取任何列表的尾部元素。

const tail = arr => arr[arr.length - 1];
console.log(tail([1,2,3])); // 3
console.log(tail(["JavaScript", "Python", "C++"])); // C++

4.19、重定向到网址

这个片段会将重定向到 URL。当重定向到网站时,这在 Web 开发中会派上用场。当用户执行任何操作时。

const redirect = (url, asLink = true) => asLink ? (window.location.href = url) : window.location.replace(url);
redirect('https://medium.com/');
redirect('https://codedev101.medium.com/');

4.20、isUpper Case

当想检查 String 是否为大写时,此片段代码将很有用。

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

4.21、isLower Case

我们看到的这个大写片段代码将检查字符串是否为小写。

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

4.22、范围生成器中的整数数组

这段代码将向你展示如何生成一个带有 n 数字且在一个范围内的随机整数数组。检查下面的代码以了解它是如何工作的。

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 ]

4.23、范围生成器中的随机整数

此片段代码用于生成给定范围内的随机整数。

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

4.24、获取类型

此片段代码可用于检查 JavaScript 中任何变量或值的类型。

const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
console.log(getType([3,4,5])); // array
console.log(getType("JavaScript"));  // string
console.log(getType(true));  // boolean

4.25、从数组中删除重复项

这段代码是从数组中删除重复项的一种快速简便的方法。

const filterNonUnique = arr => [...new Set(arr)];
console.log(filterNonUnique([2,2,5,5,7,7,8])); // [ 2,5,7,8 ] 
console.log(filterNonUnique([1,2,3,2,3] ,6])); // [1,2,3,6]

4.26、半径的度数

此片段代码将向你展示如何以快速简便的方式将度数转换为半径。

const degreeToRad = deg => (deg * Math.PI) / 180.0;
console.log(degreeToRad(80.0)); // 1.3962634015954636 
console.log(degreeToRad(360.0)); // 6.283185307179586

4.27、一年中的一天

此代码段将返回一年中的哪一天。

const dayOfYear = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
console.log(dayOfYear(new Date())); // 140

4.28、从列表中删除 False 元素

此代码段方法将从列表中删除 false 元素,如 null、false、0 或空元素。

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

4.29、检查所有相等

此代码段将检查数组的所有元素是否相等。

const AllEqual = arr => arr.every(val => val === arr[0]);
console.log(AllEqual([1, 2, 3])); // false
console.log(AllEqual([1, 2, 2])); // false
console.log(AllEqual([2, 2, 2])); // true

4.30、删除元素

这段代码是从左侧的列表中删除元素。

const drop = (arr, n = 1) => arr.slice(n);
console.log(drop([2, 4, 6])); // [4, 6] 
console.log(drop([2, 4, 6], 2)); // [6]

4.31、争取时间

此片段代码将以字符串格式从数据对象返回当前时间。

const getTime = date => date.toTimeString().slice(0, 8);
console.log(getTime(new Date())); // "10:45:12"

4.32、读取文件行

此片段代码将读取文件并将其行以数组格式存储。

const fs = require('fs');
const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
let arr = readFileLines('test.txt');
console.log(arr); // ['line 1', 'line 2', 'line 3' ,'line 4]

5、学会这20+个JavaScript单行代码,可以让你的代码更加骚气

前端潮咖出品


5.1、随机获取布尔值

此函数将使用Math.random()方法返回布尔值(真或假)。Math.random创建一个介于0和1之间的随机数,然后我们检查它是否大于或小于0.5。这意味着有50/50的机会会得到对或错。

const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());
// a 50/50 chance of returning true or false

5.2、检查日期是否为周末

通过此功能,你将能够检查提供的日期是工作日还是周末。

const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
console.log(isWeekend(new Date(2021, 4, 14))); // false (Friday)
console.log(isWeekend(new Date(2021, 4, 15))); // true (Saturday)

5.3、检查数字是偶数还是奇数

简单的实用程序功能,用于检查数字是偶数还是奇数。

const isEven = (num) => num % 2 === 0;
console.log(isEven(5)); // false
console.log(isEven(4)); // true

5.4、获取数组中的唯一值(数组去重)

从数组中删除所有重复值的非常简单的方法。此函数将数组转换为Set,然后返回数组。

const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]

5.5、检查变量是否为数组

一种检查变量是否为数组的干净简便的方法。当然,也可以有其他方法。

const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3])); // true
console.log(isArray({
    
     name: 'Ovi' })); // false
console.log(isArray('Hello World')); // false

5.6、在两个数字之间生成一个随机数

这将以两个数字为参数,并将在这两个数字之间生成一个随机数!

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50)); // could be anything from 1 - 50

5.7、生成随机字符串(唯一ID?)

也许你需要临时的唯一ID,这是一个技巧,你可以使用它在旅途中生成随机字符串。

const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());
// could be anything!!!

5.8、滚动到页面顶部

所述window.scrollTo()方法把一个X和Y坐标滚动到。如果将它们设置为零和零,我们将滚动到页面顶部。

const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();

5.9、切换布尔

切换布尔值是非常基本的编程问题之一,可以通过许多不同的方法来解决。代替使用if语句来确定将布尔值设置为哪个值,你可以使用函数使用!翻转当前值。非运算符。

// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool); // or
const toggleBool = b => !b;

5.10、交换两个变量

下面的代码是不使用第三个变量而仅使用一行代码即可交换两个变量的更简单方法之一。

[foo, bar] = [bar, foo];

5.11、计算两个日期之间的天数

要计算两个日期之间的天数,我们首先找到两个日期之间的绝对值,然后将其除以86400000(等于一天中的毫秒数),最后将结果四舍五入并返回。

const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25'))); // 199

5.12、将文字复制到剪贴板

你可能需要添加检查以查看是否存在navigator.clipboard.writeText

const copyTextToClipboard = async (text) => {
    
    
	await navigator.clipboard.writeText(text);
};

5.13、合并多个数组的不同方法

有两种合并数组的方法。其中之一是使用concat方法。另一个使用扩展运算符(…)。我们也可以使用“设置”对象从最终数组中复制任何内容。

// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];

5.14、获取javascript语言的实际类型

人们有时会使用库来查找JavaScript中某些内容的实际类型,这一小技巧可以节省你的时间(和代码大小)。

const trueTypeOf = (obj) => {
    
    
	return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log(trueTypeOf('')); // string
console.log(trueTypeOf(0)); // number
console.log(trueTypeOf()); // undefined
console.log(trueTypeOf(null)); // null
console.log(trueTypeOf({
    
    })); // object
console.log(trueTypeOf([])); // array
console.log(trueTypeOf(() => {
    
    })); // function

5.15、在结尾处截断字符串

需要从头开始截断字符串,这不是问题!

const truncateString = (string, length) => {
    
    
	return string.length < length ? string : `${
      
      string.slice(0, length - 3)}...`;
};
console.log(truncateString('Hi, I should be truncated because I am too loooong!', 36));
// Hi, I should be truncated because...

5.16、从中间截断字符串

从中间截断字符串怎么样?该函数将一个字符串作为第一个参数,然后将我们需要的字符串大小作为第二个参数,然后从第3个和第4个参数开始和结束需要多少个字符。

const truncateStringMiddle = (string, length, start, end) => {
    
    
	return `${
      
      string.slice(0, start)}...${
      
      string.slice(string.length - end)}`;
};
console.log(
	truncateStringMiddle(
		'A long story goes here but then eventually ends!', // string
		25, // 需要的字符串大小
		13, // 从原始字符串第几位开始截取
		17, // 从原始字符串第几位停止截取
	)
);
// A long story ... eventually ends!

5.17、大写字符串

好吧,不幸的是,JavaScript没有内置函数来大写字符串,但是这种解决方法可以实现。

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world')); // Hello World

5.18、检查当前选项卡是否在视图/焦点内

此简单的帮助程序方法根据选项卡是否处于视图/焦点状态而返回true或false。

const isTabInView = () => !document.hidden;  // Not hidden
isTabInView();

5.19、检查用户是否在Apple设备上

如果用户使用的是Apple设备,则返回true。

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// true/false

5.20、三元运算符

当你只想在一行中编写if…else语句时,这是一个很好的代码保护程序。

// Longhand
const age = 18;
let greetings;
if (age < 18) {
    
    
	greetings = 'You are not old enough';
} else {
    
    
	greetings = 'You are young!';
}
// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';

5.21、短路评估速记

在将变量值分配给另一个变量时,可能要确保源变量不为null,未定义或为空。可以编写带有多个条件的long if语句,也可以使用短路评估。

// Longhand
if (name !== null || name !== undefined || name !== '') {
    
    
	let fullName = name;
}
// Shorthand
const fullName = name || 'buddy';

5.22、短路评估速记

在将变量值分配给另一个变量时,可能要确保源变量不为null,未定义或为空。可以编写带有多个条件的long if语句,也可以使用短路评估。

// Longhand
if (name !== null || name !== undefined || name !== '') {
    
    
	let fullName = name;
}
// Shorthand
const fullName = name || 'buddy';

6、2021年不可错过的34种JS优化技巧

前端潮咖出品


6.1、带有多个条件的 if 语句

把多个值放在一个数组中,然后调用数组的 includes 方法。

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

6.2、 简化 if true…else

对于不包含大逻辑的 if-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;

如果有嵌套的条件,可以这么做。

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

6.3、 声明变量

当我们想要声明两个具有相同的值或相同类型的变量时,可以使用这种简写。

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

6.4、 null、undefined 和空值检查

当我们创建了新变量,有时候想要检查引用的变量是不是为非 null 或 undefined。JavaScript 确实有一个很好的快捷方式来实现这种检查。

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

6.5、null 检查和默认赋值

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // output will be ""

6.6、undefined 检查和默认赋值

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // output will be ""

一般检查

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // output: 'test'

另外,对于上述的 6.4、6.55、6.6 点,都可以使用??操作符。如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。

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

6.7、给多个变量赋值

当我们想给多个不同的变量赋值时,这种技巧非常有用。

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

6.8、简便的赋值操作符

在编程过程中,我们要处理大量的算术运算符。这是 JavaScript 变量赋值操作符的有用技巧之一。

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

6.9、if 判断值是否存在

这是我们都在使用的一种常用的简便技巧,在这里仍然值得再提一下。注意:如果 test1 有值,将执行 if 之后的逻辑,这个操作符主要用于 null 或 undefinded 检查。

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

6.10、用于多个条件判断的 && 操作符

如果只在变量为 true 时才调用函数,可以使用 && 操作符。

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

6.11、 for、for in、for of、forEach 循环

这是一种常见的循环简化技巧。

// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or  for (let i of testData)

遍历数组的每一个变量。

function testData(element, index, array) {
    
    
	console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32

6.12、比较后返回

我们也可以在 return 语句中使用比较,它可以将 5 行代码减少到 1 行。

// 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.13、箭头函数

// 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);

6.14、简短的函数调用

我们可以使用三元操作符来实现多个函数调用。

// 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)();

6.15、switch 简化

我们可以将条件保存在键值对象中,并根据条件来调用它们。

// Longhand
switch (data) {
    
    
	case 1:
		test1();
		break;
	case 2:
		test2();
		break;
	case 3:
		test();
		break;
	default:
		showToast('出错啦');
		break;
}
// Shorthand
var data = {
    
    
	1: test1,
	2: test2,
	3: test
};
data[something] && data[something]();

6.16、隐式返回

通过使用箭头函数,我们可以直接返回值,不需要 return 语句。

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

6.17、指数表示法

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

6.18、默认参数值

// 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);
add(); // output: 3

6.19、延展操作符简化

// longhand
// joining arrays using concat
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
// shorthand
// joining arrays
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]

我们也可以使用延展操作符进行克隆。

// longhand
// cloning arrays
const test1 = [1, 2, 3];
const test2 = test1.slice();
// shorthand
// cloning arrays
const test1 = [1, 2, 3];
const test2 = [...test1];

6.20、模板字面量

如果你厌倦了使用 + 将多个变量连接成一个字符串,那么这个简化技巧将让你不再头痛。

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

6.21、跨行字符串

当我们在代码中处理跨行字符串时,可以这样做。

// 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`;

6.22、对象属性赋值

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

6.23、将字符串转成数字

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

6.24、解构赋值

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

6.25、数组 find 简化

当我们有一个对象数组,并想根据对象属性找到特定对象,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' }

6.26、条件查找简化

如果我们要基于不同的类型调用不同的方法,可以使用多个 else if 语句或 switch,但有没有比这更好的简化技巧呢?

// 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();

6.27、indexOf 的按位操作简化

在查找数组的某个值时,我们可以使用 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.indexOf(item)) {
    
     
	// item not found
}

按位 (~) 运算符将返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函数。

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

6.28、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' ]
]
**/

6.29、Object.values()

这也是 ES8 中引入的一个新特性,它的功能类似于 Object.entries(),只是没有键。

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

6.30、双重按位操作

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

6.31、重复字符串多次

为了重复操作相同的字符,我们可以使用 for 循环,但其实还有一种简便的方法。

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

6.32、查找数组的最大值和最小值

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

6.33、获取字符串的字符

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

6.34、指数幂简化

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

7、20个让你的代码更优雅的JS技巧

大千世界出品


7.4、防止崩溃的可选链

如果访问未定义的属性,则会产生错误。这就是可选链的用武之地。在未定义属性时使用可选链运算符,undefined将返回而不是错误。这可以防止的代码崩溃。

const student = {
    
    
	name: "Matt",
	age: 27,
	address: {
    
    
		state: "New York",
	},
};

// LONG FORM
// Doesn't exist - Returns undefined
console.log(student && student.address && student.address.ZIPCode);

// SHORTHAND
// Doesn't exist - Returns undefined
console.log(student?.address?.ZIPCode);

7.6、将任何值转换为布尔值

可以使用!!在JS中将任何内容转换为布尔值。

console.log(!!true);    // true
console.log(!!2);       // true
console.log(!![]);      // true
console.log(!!"Test");  // true

console.log(!!false);   // false
console.log(!!0);       // false
console.log(!!"");      // false

8、演示

1.1.3X


1.1.3P

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/115985011
今日推荐