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.'复制代码
模板字面量(或模板字符串)允许嵌入表达式。它具有独特的语法,该字符串必须用反引号(``)括起来。模板字符串提供了可以包含动态值的占位符,以美元符号和大括号标记(${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);复制代码
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));复制代码
输出结果:
3. 值为数字
您是否曾经注意到,即使输入框的类型为数字,event.target.value
仍始终返回字符串类型的值?
请参见下面的示例。我们有一个简单的数字类型的文本框。这意味着它仅接受数字作为输入,它具有事件处理程序来处理按键事件。
<input>复制代码
在事件处理程序中,我们使用event.target.value
取出值,但是它返回一个字符串类型值。现在,我将不得不将其解析为整数。如果输入框接受浮点数(例如 16.56)怎么办?使用 parseFloat()
然后呢?啊,我不得不面对各种各样的困惑和额外的工作!
function trackChange(event) { let value = event.target.value; console.log(`is ${value} a number?`, Number.isInteger(value)); }复制代码
请改用event.target.valueAsNumber
,它以数字形式返回值。
let valueAsNumber = event.target.valueAsNumber;console.log(`is ${value} a number?`, Number.isInteger(valueAsNumber));复制代码
4. 使用 && 运算符化简表达式
让我们考虑一个具有布尔值和函数的情况。
let isPrime = true;const startWatching = () => { console.log('Started Watching!'); }复制代码
像下面这样,通过检查布尔值来确定是否调用函数,代码太多了。
if (isPrime) { startWatching(); }复制代码
能否通过 AND(&&)运算符使用简写形式?是的,完全可以避免使用 if 语句。酷吧!
isPrime && startWatching();复制代码
5. 使用 || 运算符处理默认值
如果您想为变量设置默认值,可以使用 OR(||)运算符轻松实现。
let person = {name: 'Jack'};let age = person.age || 35; // 如果 age 未定义,则将值设置为 35console.log(`Age of ${person.name} is ${age}`);复制代码
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);复制代码
通过指定最小值和最大值,在一个范围内生成一个随机数,
let getRandom = (min, max) => { return Math.round(Math.random() * (max - min) + min); }console.log('Get random', getRandom(0, 10));复制代码
7. 函数默认参数
在JavaScript中,函数实参(或形参)就像该函数的局部变量一样。调用函数时,您可以传递也可以不传递值。如果您不为参数传递值,则该值将是undefined
,并且可能会导致一些多余的副作用。
有一种在定义参数时将默认值传递给函数参数的简单方法。在以下示例中,我们将默认值Hello
传递给greetings
函数的参数message
。
let greetings = (name, message='Hello,') => { return `${message} ${name}`; }console.log(greetings('Jack'));console.log(greetings('Jack', 'Hola!'));复制代码
8. 必需的函数参数
基于默认参数的特性,我们可以将参数作为必需参数。首先定义一个函数以使用错误消息抛出错误,
let isRequired = () => { throw new Error('This is a mandatory parameter.'); }复制代码
然后将函数作为必需参数的默认值。请记住,在调用函数时如果为参数传递值,那么默认值会被忽略。但是,如果参数值为“undefined”,则默认值会被使用。
let greetings = (name=isRequired(), message='Hello,') => { return `${message} ${name}`; }console.log(greetings());复制代码
在上面的代码中,name
将是未定义的,因此将会尝试使用默认值,即 isRequired()
函数。 它将引发如下所示的错误:
9. 逗号运算符
当我意识到逗号(,
) 是一个单独的运算符,并且我此前从未注意到时,我感到很惊讶。我已经在代码中使用了大量逗号,但是从未意识到它的其它用途。
运算符用于从左到右计算其每个操作数,并返回最后一个操作数的值。
let count = 1;let ret = (count++, count);console.log(ret);复制代码
在上面的示例中,变量ret
的值将为 2。同理,下面的代码将在控制台中输出值 32 记录到控制台中。
let val = (12, 32);console.log(val);复制代码
我们在哪里使用它?有什么想法吗?逗号 (,
)运算符最常见的用法是在 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'};复制代码
使用扩展运算符将它们合并为
// spread operatorlet merged = {...emp, ...job};console.log('Spread merged', merged);复制代码
还有另一种实现合并的方法。你可以像下面这样使用 Object.assign()
:
console.log('Object assign', Object.assign({}, emp, job));复制代码
输出结果:
注意,扩展运算符和 Object.assign
都执行浅合并。在浅合并中,第一个对象的属性将被第二个对象的相同属性值覆盖。
要进行深度合并,可以考虑使用 lodash 中的 _merge
。
11. 解构
将数组元素和对象属性分解为变量的技术称为“解构”。让我们看几个例子,
数组
在这里,我们有一系列的表情符号,
let emojis = ['', '⏲️', '', ''];复制代码
为了解构,我们将使用以下语法,
let [fire, clock, , watermelon] = emojis;复制代码
这与let fire = emojis [0];
相同,但具有更大的灵活性。您是否注意到,我只是在奖杯表情符号的位置上使用了空格而忽略了它?那么,这将输出什么呢?
console.log(fire, clock, watermelon);复制代码
输出结果:
让我在这里再介绍一个叫做“rest”运算符的东西。如果您想对数组进行解构,从而将一个或多个项目分配给变量并将其余部分暂放在另一个数组中,就可以使用...rest
来完成,如下所示。
let [fruit, ...rest] = emojis;console.log(rest);复制代码
输出结果:
对象
像数组一样,我们也可以解构对象。
let shape = { name: 'rect', sides: 4, height: 300, width: 500};复制代码
像下面这样进行解构,我们可以把对象的 name
属性和 sides
属性赋值给两个变量,而其余的属性则存放在另一个对象中。
let {name, sides, ...restObj} = shape;console.log(name, sides);console.log(restObj);复制代码
输出结果:
阅读有关此主题的更多信息 from here.
12. 交换变量
现在,使用我们刚刚学习的解构,变量交换将会变得非常容易。
let fire = '';let fruit = ''; [fruit, fire] = [fire, fruit];console.log(fire, fruit);复制代码
13. isArray
确定输入是否为数组的另一种有用方法。
let emojis = ['', '⏲️', '', ''];console.log(Array.isArray(emojis));let obj = {};console.log(Array.isArray(obj));复制代码
14. undefined 和 null
undefined
指的是还没有给变量定义值,但已经声明了该变量。
null
本身是一个空且不存在的值,必须将其显式赋值给变量。
undefined
和null
并不严格相等,
undefined === null // false复制代码
阅读有关此主题的更多信息 from here.
15. 获取查询参数
window.location
对象具有许多实用方法和属性。使用这些属性和方法,我们可以从浏览器 URL 中获取有关协议、主机、端口、域等的信息。
下面是我发现的一个非常有用的属性:
window.location.search复制代码
search
属性从位置 url 返回查询字符串。以这个 url 为例:https://tapasadhiary.com?project = js
。 location.search
将返回?project = js
我们可以使用另一个名为URLSearchParams
的有用接口以及location.search
来获取查询参数的值。
let project = new URLSearchParams(location.search).get('project');复制代码
输出结果: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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.