Table of Contents
本文目的
1. 使用模板字符串
2. isInteger
3. 值为数字
4. 使用 && 运算符化简表达式
5. 使用 || 运算符处理默认值
6. 获取随机项
7. 函数默认参数
8. 必需的函数参数
9. 逗号运算符
10. 合并多个对象
11. 解构
数组
对象
12. 交换变量
13. isArray
14. undefined 和 null
15. 获取查询参数
Home Web Front-end JS Tutorial Fifteen JavaScript Programming Tips

Fifteen JavaScript Programming Tips

Oct 26, 2020 pm 05:34 PM
javascript

JavaScript栏目放送十五条JavaScript编程技巧。

本文目的

大多数编程语言都足够开放,以允许程序员以多种方式得到类似的结果。JavaScript 也是如此,使用 JavaScript,我们通常可以通过多种方法来达到相似的结果,虽然有时会造成混淆。

其中一些用法比其他方法要好,而这些就是我要分享的。我将在本文中一一列举,我敢肯定,您在阅读本文时会发现,在很多地方您和我的做法是相同的。

1. 使用模板字符串

使用 运算符拼接字符串来构建有意义的字符串,这是过时的做法。此外,将字符串与动态值(或表达式)连接可能会导致计算或表达错误。

let name = 'Charlse';let place = 'India';let isPrime = bit => {  return (bit === 'P' ? 'Prime' : 'Nom-Prime');
}// 使用`+`运算符的字符串连接let messageConcat = 'Mr. ' + name + ' is from ' + place + '. He is a' + ' ' + isPrime('P') + ' member.'复制代码
Copy after login

模板字面量(或模板字符串)允许嵌入表达式。它具有独特的语法,该字符串必须用反引号(``)括起来。模板字符串提供了可以包含动态值的占位符,以美元符号和大括号标记(${expression})。

以下是一个演示它的例子,

let name = 'Charlse';let place = 'India';let isPrime = bit => {  return (bit === 'P' ? 'Prime' : 'Nom-Prime');
}// 使用模板字符串let messageTemplateStr = `Mr. ${name} is from ${place}. He is a ${isPrime('P')} member.`console.log(messageTemplateStr);复制代码
Copy after login

2. isInteger

有一种更简洁的方法可以知道值是否为整数。JavaScript 的 Number API 提供了名为 isInteger() 的方法来实现此目的。这是非常有用的,最好了解一下。

let mynum = 123;let mynumStr = "123";console.log(`${mynum} is a number?`, Number.isInteger(mynum));console.log(`${mynumStr} is a number?`, Number.isInteger(mynumStr));复制代码
Copy after login

输出结果:

Fifteen JavaScript Programming Tips

3. 值为数字

您是否曾经注意到,即使输入框的类型为数字,event.target.value仍始终返回字符串类型的值?

请参见下面的示例。我们有一个简单的数字类型的文本框。这意味着它仅接受数字作为输入,它具有事件处理程序来处理按键事件。

<input>复制代码
Copy after login

在事件处理程序中,我们使用event.target.value取出值,但是它返回一个字符串类型值。现在,我将不得不将其解析为整数。如果输入框接受浮点数(例如 16.56)怎么办?使用 parseFloat() 然后呢?啊,我不得不面对各种各样的困惑和额外的工作!

function trackChange(event) {   let value = event.target.value;   console.log(`is ${value} a number?`, Number.isInteger(value));
}复制代码
Copy after login

请改用event.target.valueAsNumber,它以数字形式返回值。

let valueAsNumber = event.target.valueAsNumber;console.log(`is ${value} a number?`, Number.isInteger(valueAsNumber));复制代码
Copy after login

4. 使用 && 运算符化简表达式

让我们考虑一个具有布尔值和函数的情况。

let isPrime = true;const startWatching = () => {    console.log('Started Watching!');
}复制代码
Copy after login

像下面这样,通过检查布尔值来确定是否调用函数,代码太多了。

if (isPrime) {
    startWatching();
}复制代码
Copy after login

能否通过 AND(&&)运算符使用简写形式?是的,完全可以避免使用 if 语句。酷吧!

isPrime && startWatching();复制代码
Copy after login

5. 使用 || 运算符处理默认值

如果您想为变量设置默认值,可以使用 OR(||)运算符轻松实现。

let person = {name: 'Jack'};let age = person.age || 35; // 如果 age 未定义,则将值设置为 35console.log(`Age of ${person.name} is ${age}`);复制代码
Copy after login

6. 获取随机项

生成随机数或从数组中获取随机项是非常有用且方便的方法。我已经在我的许多项目中多次看到它们了。

从数组中获取随机项,

let planets = ['Mercury ', 'Mars', 'Venus', 'Earth', 'Neptune', 'Uranus', 'Saturn', 'Jupiter'];let randomPlanet = planets[Math.floor(Math.random() * planets.length)];console.log('Random Planet', randomPlanet);复制代码
Copy after login

通过指定最小值和最大值,在一个范围内生成一个随机数,

let getRandom = (min, max) => {    return Math.round(Math.random() * (max - min) + min);
}console.log('Get random', getRandom(0, 10));复制代码
Copy after login

7. 函数默认参数

在JavaScript中,函数实参(或形参)就像该函数的局部变量一样。调用函数时,您可以传递也可以不传递值。如果您不为参数传递值,则该值将是undefined,并且可能会导致一些多余的副作用。

有一种在定义参数时将默认值传递给函数参数的简单方法。在以下示例中,我们将默认值Hello传递给greetings函数的参数message

let greetings = (name, message='Hello,') => {    return `${message} ${name}`;
}console.log(greetings('Jack'));console.log(greetings('Jack', 'Hola!'));复制代码
Copy after login

8. 必需的函数参数

基于默认参数的特性,我们可以将参数作为必需参数。首先定义一个函数以使用错误消息抛出错误,

let isRequired = () => {    throw new Error('This is a mandatory parameter.');
}复制代码
Copy after login

然后将函数作为必需参数的默认值。请记住,在调用函数时如果为参数传递值,那么默认值会被忽略。但是,如果参数值为“undefined”,则默认值会被使用。

let greetings = (name=isRequired(), message='Hello,') => {    return `${message} ${name}`;
}console.log(greetings());复制代码
Copy after login

在上面的代码中,name将是未定义的,因此将会尝试使用默认值,即 isRequired() 函数。 它将引发如下所示的错误:

9. 逗号运算符

当我意识到逗号(,) 是一个单独的运算符,并且我此前从未注意到时,我感到很惊讶。我已经在代码中使用了大量逗号,但是从未意识到它的其它用途。

运算符用于从左到右计算其每个操作数,并返回最后一个操作数的值。

let count = 1;let ret = (count++, count);console.log(ret);复制代码
Copy after login

在上面的示例中,变量ret的值将为 2。同理,下面的代码将在控制台中输出值 32 记录到控制台中。

let val = (12, 32);console.log(val);复制代码
Copy after login

我们在哪里使用它?有什么想法吗?逗号 (,)运算符最常见的用法是在 for 循环中提供多个参数。

for (var i = 0, j = 50; i <h2 id="合并多个对象">10. 合并多个对象</h2><p>您可能需要将两个对象合并在一起,并创建一个更好的、内容更丰富的对象来使用。为此,您可以使用扩展运算符<code>...</code>(对的,就是三个点!)。</p><p>分别考虑 <code>emp</code> 和 <code>job</code> 这两个对象,</p><pre class="brush:php;toolbar:false">let emp = { 'id': 'E_01', 'name': 'Jack', 'age': 32, 'addr': 'India'};let job = { 'title': 'Software Dev',  'location': 'Paris'};复制代码
Copy after login

使用扩展运算符将它们合并为

// spread operatorlet merged = {...emp, ...job};console.log('Spread merged', merged);复制代码
Copy after login

还有另一种实现合并的方法。你可以像下面这样使用 Object.assign()

console.log('Object assign', Object.assign({}, emp, job));复制代码
Copy after login

输出结果:

注意,扩展运算符和 Object.assign 都执行浅合并。在浅合并中,第一个对象的属性将被第二个对象的相同属性值覆盖。

要进行深度合并,可以考虑使用 lodash 中的 _merge

11. 解构

将数组元素和对象属性分解为变量的技术称为“解构”。让我们看几个例子,

数组

在这里,我们有一系列的表情符号,

let emojis = ['', '⏲️', '', ''];复制代码
Copy after login

为了解构,我们将使用以下语法,

let [fire, clock, , watermelon] = emojis;复制代码
Copy after login

这与let fire = emojis [0];相同,但具有更大的灵活性。您是否注意到,我只是在奖杯表情符号的位置上使用了空格而忽略了它?那么,这将输出什么呢?

console.log(fire, clock, watermelon);复制代码
Copy after login

输出结果:

Fifteen JavaScript Programming Tips

让我在这里再介绍一个叫做“rest”运算符的东西。如果您想对数组进行解构,从而将一个或多个项目分配给变量并将其余部分暂放在另一个数组中,就可以使用...rest来完成,如下所示。

let [fruit, ...rest] = emojis;console.log(rest);复制代码
Copy after login

输出结果:

Fifteen JavaScript Programming Tips

对象

像数组一样,我们也可以解构对象。

let shape = {  name: 'rect',  sides: 4,  height: 300,  width: 500};复制代码
Copy after login

像下面这样进行解构,我们可以把对象的 name 属性和 sides 属性赋值给两个变量,而其余的属性则存放在另一个对象中。

let {name, sides, ...restObj} = shape;console.log(name, sides);console.log(restObj);复制代码
Copy after login

输出结果:

Fifteen JavaScript Programming Tips

阅读有关此主题的更多信息 from here.

12. 交换变量

现在,使用我们刚刚学习的解构,变量交换将会变得非常容易。

let fire = '';let fruit = '';

[fruit, fire] = [fire, fruit];console.log(fire, fruit);复制代码
Copy after login

13. isArray

确定输入是否为数组的另一种有用方法。

let emojis = ['', '⏲️', '', ''];console.log(Array.isArray(emojis));let obj = {};console.log(Array.isArray(obj));复制代码
Copy after login

14. undefined 和 null

undefined指的是还没有给变量定义值,但已经声明了该变量。

null本身是一个空且不存在的值,必须将其显式赋值给变量。

undefinednull并不严格相等,

undefined === null // false复制代码
Copy after login

阅读有关此主题的更多信息 from here.

15. 获取查询参数

window.location对象具有许多实用方法和属性。使用这些属性和方法,我们可以从浏览器 URL 中获取有关协议、主机、端口、域等的信息。

下面是我发现的一个非常有用的属性:

window.location.search复制代码
Copy after login

search属性从位置 url 返回查询字符串。以这个 url 为例:https://tapasadhiary.com?project = jslocation.search将返回?project = js

我们可以使用另一个名为URLSearchParams的有用接口以及location.search来获取查询参数的值。

let project = new URLSearchParams(location.search).get('project');复制代码
Copy after login

输出结果:js

阅读有关此主题的更多信息 from here.

相关免费学习推荐:javascript(视频)

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles