Home > Web Front-end > JS Tutorial > body text

Tips for using JavaScript worth collecting

青灯夜游
Release: 2019-11-29 15:25:41
forward
2325 people have browsed it

Tips for using JavaScript worth collecting

Any technology will have some tips of its own in practice. Similarly, there are some tips when using JavaScript, but they may be easily overlooked in many cases. On the Internet, many colleagues in the industry will summarize (or collect) some tips in this area from time to time.

As a JavaScript rookie, you should pay more attention to these tips, because these tips can help us solve problems in actual business development, and they will be easy to solve. In this article, we will compile some tips about JavaScript that everyone is familiar with or unfamiliar with.

[Related course recommendations: JavaScript video tutorial]

Array

Let’s first look at how to use it Some common tricks used in arrays.

Array deduplication

ES6 provides several concise array deduplication methods, but this method is not suitable for processing non-basic types array. For basic type array deduplication, you can use... new Set() to filter out duplicate values ​​in the array and create a new array with only unique values.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);

> Result:(4) [1, 2, 3, 5]
Copy after login

This is a new feature in ES6. Before ES6, to achieve the same effect, we needed to use more code. This technique works for arrays containing basic types: undefined, null, boolean, string, and number. If the array contains an object, function or other array, you need to use another method.

In addition to the above method, you can also use Array.from(new Set()) to achieve it:

const array = [1, 1, 2, 3, 5, 5, 1]
Array.from(new Set(array))

> Result:(4) [1, 2, 3, 5]
Copy after login

In addition, you can also use Array's .filter and indexOf() to achieve it :

const array = [1, 1, 2, 3, 5, 5, 1]
array.filter((arr, index) => array.indexOf(arr) === index)

> Result:(4) [1, 2, 3, 5]
Copy after login

Note that the indexOf() method will return the first occurrence of the array item in the array. That's why we can compare the index returned by the indexOf() method with the current index on each iteration to determine if the current item is a duplicate.

Ensure the length of the array

When dealing with the grid structure, if the length of each row of the original data is not equal, you need to recreate the data. In order to ensure that the data length of each row is equal, you can use Array.fill to process:

let array = Array(5).fill('');
console.log(array);

> Result: (5) ["", "", "", "", ""]
Copy after login

Array mapping

Do not use Array.map Method for mapping array values.

const array = [
    {
        name: '大漠',
        email: 'w3cplus@hotmail.com'
    },
    {
        name: 'Airen',
        email: 'airen@gmail.com'
    }
]
const name = Array.from(array, ({ name }) => name)

> Result: (2) ["大漠", "Airen"]
Copy after login

Array truncation

If you want to remove values ​​from the end of the array (remove the last item in the array), there is a better way than using splice( ) a faster alternative.

For example, if you know the size of the original array, you can redefine the value of the length attribute of the array to delete the value from the end of the array:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array.length)
> Result: 10

array.length = 4
console.log(array)
> Result: (4) [0, 1, 2, 3]
Copy after login

This is a particularly concise solution. However, the slice() method runs faster and has better performance:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);

console.log(array); 
> Result: [0, 1, 2, 3]
Copy after login

Filter out falsy values ​​in the array

If you want to filter Falsy values ​​in the array, such as 0, undefined, null, false, can be implemented through the map and filter methods:

const array = [0, 1, '0', '1', '大漠', 'w3cplus.com', undefined, true, false, null, 'undefined', 'null', NaN, 'NaN', '1' + 0]
array.map(item => {
    return item
}).filter(Boolean)

> Result: (10) [1, "0", "1", "大漠", "w3cplus.com", true, "undefined", "null", "NaN", "10"]
Copy after login

Get the last item of the array

When the slice() value of the array is a positive value, the array items are intercepted from the beginning of the array. If the value is a negative integer, the array items can be obtained from the end of the array.

let array = [1, 2, 3, 4, 5, 6, 7]

const firstArrayVal = array.slice(0, 1)
> Result: [1]

const lastArrayVal = array.slice(-1)
> Result: [7]

console.log(array.slice(1))
> Result: (6) [2, 3, 4, 5, 6, 7]

console.log(array.slice(array.length))
> Result: []
Copy after login

As shown in the above example, use array.slice(-1) to get the last item of the array. In addition, you can also use the following method to get the last item of the array:

console.log(array.slice(array.length - 1))
> Result: [7]
Copy after login

Filter and sort a list of strings

You may have a list of many names and need to filter out duplicate names and sort them alphabetically .

In our example we prepared a list of JavaScript reserved words for different versions of the language, but as you can see, there are a lot of duplicate keywords and they are not arranged in alphabetical order. So this is a perfect list of strings (array) to test our JavaScript knowledge.

var keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'final', 'float', 'short', 'super', 'throw', 'while', 'delete', 'double', 'export', 'import', 'native', 'public', 'return', 'static', 'switch', 'throws', 'typeof', 'boolean', 'default', 'extends', 'finally', 'package', 'private', 'abstract', 'continue', 'debugger', 'function', 'volatile', 'interface', 'protected', 'transient', 'implements', 'instanceof', 'synchronized', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'await', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof'];
Copy after login

Since we don’t want to change our original list, we are going to use a higher order function called filter, which will return a new filtered array based on the callback method we passed. The callback method will compare the index of the current keyword in the original list with the index in the new list, and only push the current keyword to the new array if the index matches.

Finally we are ready to use the sort method to sort the filtered list. sort only accepts a comparison method as a parameter and returns the list sorted alphabetically.

Using arrow functions under ES6 seems simpler:

const filteredAndSortedKeywords = keywords
    .filter((keyword, index) => keywords.lastIndexOf(keyword) === index)
    .sort((a, b) => a < b ? -1 : 1);
Copy after login

This is the final filtered and sorted list of JavaScript reserved words:

console.log(filteredAndSortedKeywords);

> Result: [&#39;abstract&#39;, &#39;arguments&#39;, &#39;await&#39;, &#39;boolean&#39;, &#39;break&#39;, &#39;byte&#39;, &#39;case&#39;, &#39;catch&#39;, &#39;char&#39;, &#39;class&#39;, &#39;const&#39;, &#39;continue&#39;, &#39;debugger&#39;, &#39;default&#39;, &#39;delete&#39;, &#39;do&#39;, &#39;double&#39;, &#39;else&#39;, &#39;enum&#39;, &#39;eval&#39;, &#39;export&#39;, &#39;extends&#39;, &#39;false&#39;, &#39;final&#39;, &#39;finally&#39;, &#39;float&#39;, &#39;for&#39;, &#39;function&#39;, &#39;goto&#39;, &#39;if&#39;, &#39;implements&#39;, &#39;import&#39;, &#39;in&#39;, &#39;instanceof&#39;, &#39;int&#39;, &#39;interface&#39;, &#39;let&#39;, &#39;long&#39;, &#39;native&#39;, &#39;new&#39;, &#39;null&#39;, &#39;package&#39;, &#39;private&#39;, &#39;protected&#39;, &#39;public&#39;, &#39;return&#39;, &#39;short&#39;, &#39;static&#39;, &#39;super&#39;, &#39;switch&#39;, &#39;synchronized&#39;, &#39;this&#39;, &#39;throw&#39;, &#39;throws&#39;, &#39;transient&#39;, &#39;true&#39;, &#39;try&#39;, &#39;typeof&#39;, &#39;var&#39;, &#39;void&#39;, &#39;volatile&#39;, &#39;while&#39;, &#39;with&#39;, &#39;yield&#39;]
Copy after login

Clearing an array

If you define an array and then you want to clear it. Normally, you would do this:

let array = [1, 2, 3, 4];
function emptyArray() {
    array = [];
}
emptyArray();
Copy after login

However, there is a more efficient way to clear the array. You can write like this:

let array = [1, 2, 3, 4];
function emptyArray() {
    array.length = 0;
}
emptyArray();
Copy after login

flatten multidimensional array

使用...运算符,将多维数组拍平:

const arr = [1, [2, &#39;大漠&#39;], 3, [&#39;blog&#39;, &#39;1&#39;, 2, 3]]
const flatArray = [].concat(...arr)
console.log(flatArray)

> Result: (8) [1, 2, "大漠", 3, "blog", "1", 2, 3]
Copy after login

不过上面的方法只适用于二维数组。不过通过递归调用,可以使用它适用于二维以下的数组:

function flattenArray(arr) {  
    const flattened = [].concat(...arr);  
    return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened;
}
const array = [1, [2, &#39;大漠&#39;], 3, [[&#39;blog&#39;, &#39;1&#39;], 2, 3]]
const flatArr = flattenArray(array)
console.log(flatArr)

> Result: (8) [1, 2, "大漠", 3, "blog", "1", 2, 3]
Copy after login

从数组中获取最大值和最小值

可以使用Math.max和Math.min取出数组中的最大小值和最小值:

const numbers = [15, 80, -9, 90, -99]
const maxInNumbers = Math.max.apply(Math, numbers)
const minInNumbers = Math.min.apply(Math, numbers)

console.log(maxInNumbers)
> Result: 90

console.log(minInNumbers)
> Result: -99
Copy after login

另外还可以使用ES6的...运算符来完成:

const numbers = [1, 2, 3, 4];
Math.max(...numbers) 
> Result: 4

Math.min(...numbers) 
> > Result: 1
Copy after login

对象

在操作对象时也有一些小技巧。

使用...运算符合并对象或数组中的对象

同样使用ES的...运算符可以替代人工操作,合并对象或者合并数组中的对象。

// 合并对象
const obj1 = {
    name: &#39;大漠&#39;,
    url: &#39;w3cplus.com&#39;
}
const obj2 = {
    name: &#39;airen&#39;,
    age: 30
}
const mergingObj = {...obj1, ...obj2}
> Result: {name: "airen", url: "w3cplus.com", age: 30}

// 合并数组中的对象
const array = [
    {
        name: &#39;大漠&#39;,
        email: &#39;w3cplus@gmail.com&#39;
    },
    {
        name: &#39;Airen&#39;,
        email: &#39;airen@gmail.com&#39;
    }
]
const result = array.reduce((accumulator, item) => {
    return {
        ...accumulator,
        [item.name]: item.email
    }
}, {})
> Result: {大漠: "w3cplus@gmail.com", Airen: "airen@gmail.com"}
Copy after login

有条件的添加对象属性

不再需要根据一个条件创建两个不同的对象,以使它具有特定的属性。为此,使用...操作符是最简单的。

const getUser = (emailIncluded) => {
    return {
        name: &#39;大漠&#39;,
        blog: &#39;w3cplus&#39;,
        ...emailIncluded && {email: &#39;w3cplus@hotmail.com&#39;}
    }
}

const user = getUser(true)
console.log(user)
> Result: {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com"}

const userWithoutEmail = getUser(false)
console.log(userWithoutEmail)
> Result: {name: "大漠", blog: "w3cplus"}
Copy after login

解构原始数据

你可以在使用数据的时候,把所有数据都放在一个对象中。同时想在这个数据对象中获取自己想要的数据。在这里可以使用ES6的Destructuring特性来实现。比如你想把下面这个obj中的数据分成两个部分:

const obj = {
    name: &#39;大漠&#39;,
    blog: &#39;w3cplus&#39;,
    email: &#39;w3cplus@hotmail.com&#39;,
    joined: &#39;2019-06-19&#39;,
    followers: 45
}
let user = {}, userDetails = {}

({name: user.name, email: user.email, ...userDetails} = obj)
> {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com", joined: "2019-06-19", followers: 45}

console.log(user)
> Result: {name: "大漠", email: "w3cplus@hotmail.com"}

console.log(userDetails)
> Result: {blog: "w3cplus", joined: "2019-06-19", followers: 45}
Copy after login

动态更改对象的key

在过去,我们首先必须声明一个对象,然后在需要动态属性名的情况下分配一个属性。在以前,这是不可能以声明的方式实现的。不过在ES6中,我们可以实现:

const dynamicKey = &#39;email&#39;
let obj = {
    name: &#39;大漠&#39;,
    blog: &#39;w3cplus&#39;,
    [dynamicKey]: &#39;w3cplus@hotmail.com&#39;
}

console.log(obj)
> Result: {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com"}
Copy after login

判断对象的数据类型

使用Object.prototype.toString配合闭包来实现对象数据类型的判断:

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isArray = isType(&#39;Array&#39;)([1, 2, 3])

console.log(isArray)
> Result: true
Copy after login

上面的代码相当于:

function isType(type){
    return function (target) {
        return `[object ${type}]` === Object.prototype.toString.call(target)
    }
}

isType(&#39;Array&#39;)([1,2,3])
> Result: true
Copy after login

或者:

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isString = isType(&#39;String&#39;)
const res = isString((&#39;1&#39;))

console.log(res)
> Result: true
Copy after login

检查某对象是否有某属性

当你需要检查某属性是否存在于一个对象,你可能会这样做:

var obj = {
    name: &#39;大漠&#39;
};
if (obj.name) { 
    console.log(true) // > Result: true
}
Copy after login

这是可以的,但是你需要知道有两种原生方法可以解决此类问题。in 操作符 和 Object.hasOwnProperty,任何继承自Object的对象都可以使用这两种方法。

var obj = {
    name: &#39;大漠&#39;
};
obj.hasOwnProperty(&#39;name&#39;);     // > true
&#39;name&#39; in obj;             // > true

obj.hasOwnProperty(&#39;valueOf&#39;);  // > false, valueOf 继承自原型链
&#39;valueOf&#39; in obj;          // > true
Copy after login

两者检查属性的深度不同,换言之hasOwnProperty只在本身有此属性时返回true,而in操作符不区分属性来自于本身或继承自原型链。

这是另一个例子:

var myFunc = function() {
    this.name = &#39;大漠&#39;;
};
myFunc.prototype.age = &#39;10 days&#39;;
var user = new myFunc();

user.hasOwnProperty(&#39;name&#39;); 
> Result: true

user.hasOwnProperty(&#39;age&#39;); 
> Result: false,   //  因为age来自于原型链
Copy after login

创造一个纯对象

使用Object.create(null)可以创建一个纯对象,它不会从Object类继承任何方法(例如:构造函数、toString() 等):

const pureObject = Object.create(null);

console.log(pureObject);                //=> {}
console.log(pureObject.constructor);    //=> undefined
console.log(pureObject.toString);       //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
Copy after login

数据类型转换

JavaScript中数据类型有NumberStringBooleanObjectArrayFunction等,在实际使用时会碰到数据类型的转换。在转换数据类型时也有一些小技巧。

转换为布尔值

布尔值除了true和false之外,JavaScript还可以将所有其他值视为“真实的”或“虚假的”。除非另有定义,JavaScript中除了0、''、null、undefined、NaN和false之外的值都是真实的。

我们可以很容易地在真和假之间使用!运算符进行切换,它也会将类型转换为Boolean。比如:

const isTrue = !0;
const isFasle = !1;
const isFasle = !!0 // !0 => true,true的反即是false

console.log(isTrue)
> Result: true

console.log(typeof isTrue)
> Result: &#39;boolean&#39;
Copy after login

这种类型的转换在条件语句中非常方便,比如将!1当作false。

转换为字符串

我们可以使用运算符+后紧跟一组空的引号''快速地将数字或布尔值转为字符串:

const val = 1 + &#39;&#39;
const val2 = false + &#39;&#39;

console.log(val)
>  Result: "1"

console.log(typeof val)
> Result: "string"

console.log(val2)
> Result: "false"

console.log(typeof val2)
> Result: "string"
Copy after login

转换为数值

上面我们看到了,使用+紧跟一个空的字符串''就可以将数值转换为字符串。相反的,使用加法运算符+可以快速实现相反的效果。

let int = &#39;12&#39;
int = +int

console.log(int)
> Result: 12

console.log(typeof int)
> Result: &#39;number&#39;
Copy after login

用同样的方法可以将布尔值转换为数值:

console.log(+true)
> Return: 1

console.log(+false)
> Return: 0
Copy after login

在某些上下文中,+会被解释为连接操作符,而不是加法运算符。当这种情况发生时,希望返回一个整数,而不是浮点数,那么可以使用两个波浪号~~。双波浪号~~被称为按位不运算符,它和-n - 1等价。例如, ~15 = -16。这是因为- (-n - 1) - 1 = n + 1 - 1 = n。换句话说,~ - 16 = 15。

我们也可以使用~~将数字字符串转换成整数型:

const int = ~~&#39;15&#39;

console.log(int)
> Result: 15

console.log(typeof int)
> Result: &#39;number&#39;
Copy after login

同样的,NOT操作符也可以用于布尔值: ~true = -2~false = -1

浮点数转换为整数

平常都会使用Math.floor()Math.ceil()Math.round()将浮点数转换为整数。在JavaScript中还有一种更快的方法,即使用|(位或运算符)将浮点数截断为整数。

console.log(23.9 | 0);  
> Result: 23

console.log(-23.9 | 0); 
> Result: -23
Copy after login

|的行为取决于处理的是正数还是负数,所以最好只在确定的情况下使用这个快捷方式。

如果n是正数,则n | 0有效地向下舍入。如果n是负数,它有效地四舍五入。更准确的说,该操作删除小数点后的内容,将浮点数截断为整数。还可以使用~~来获得相同的舍入效果,如上所述,实际上任何位操作符都会强制浮点数为整数。这些特殊操作之所以有效,是因为一旦强制为整数,值就保持不变。

|还可以用于从整数的末尾删除任意数量的数字。这意味着我们不需要像下面这样来转换类型:

let str = "1553";

Number(str.substring(0, str.length - 1));
> Result: 155
Copy after login

我们可以像下面这样使用|运算符来替代:

console.log(1553 / 10   | 0)  
> Result: 155

console.log(1553 / 100  | 0)  
> Result: 15

console.log(1553 / 1000 | 0)  
> Result: 1
Copy after login

使用!!操作符转换布尔值

有时候我们需要对一个变量查检其是否存在或者检查值是否有一个有效值,如果存在就返回true值。为了做这样的验证,我们可以使用!!操作符来实现是非常的方便与简单。

对于变量可以使用!!variable做检测,只要变量的值为:0、null、" "、undefined或者NaN都将返回的是false,反之返回的是true。比如下面的示例:

function Account(cash) {
    this.cash = cash;
    this.hasMoney = !!cash;
}

var account = new Account(100.50);
console.log(account.cash); 
> Result: 100.50

console.log(account.hasMoney); 
> Result: true

var emptyAccount = new Account(0);
console.log(emptyAccount.cash); 
> Result: 0

console.log(emptyAccount.hasMoney); 
> Result: false
Copy after login

在这个示例中,只要account.cash的值大于0,那么account.hasMoney返回的值就是true。

还可以使用!!操作符将truthy或falsy值转换为布尔值:

!!""        // > false
!!0         // > false
!!null      // > false
!!undefined  // > false
!!NaN       // > false

!!"hello"   // > true
!!1         // > true
!!{}        // > true
!![]        // > true
Copy after login

小结

文章主要收集和整理了一些有关于JavaScript使用的小技巧。既然是技巧在必要的时候能帮助我们快速的解决一些问题。如果你有这方面的相关积累,欢迎在下面的评论中与我们一起分享。后续将会持续更新,希望对大家有所帮助。

本文来自 js教程 栏目,欢迎学习!

The above is the detailed content of Tips for using JavaScript worth collecting. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:w3cplus.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template