search
HomeWeb Front-endJS TutorialSome tips for JavaScript

Some tips for JavaScript

Jan 16, 2017 pm 01:40 PM

This article mainly introduces the relevant information collected by JavaScript tips. Friends who need it can refer to it. I hope to provide you with these short and practical JavaScript tips to improve your programming ability.

Use the !! operator to convert a Boolean value

Sometimes we need to check whether a variable exists or check whether the value has a valid value, and return it if it exists true value. In order to do such verification, we can use the !! operator, which is very convenient and simple. You can use !!variable to detect variables. As long as the value of the variable is: 0, null, " ", undefined or NaN, it will return false, otherwise it will return true. For example, the following example:

function Account(cash) {
    this.cash = cash;
    this.hasMoney = !!cash;
}
var account = new Account(100.50);
console.log(account.cash); // 100.50
console.log(account.hasMoney); // true
var emptyAccount = new Account(0);
console.log(emptyAccount.cash); // 0
console.log(emptyAccount.hasMoney); // false

In this example, as long as the value of account.cash is greater than 0, the value returned by account.hasMoney is true.

Use + to convert strings into numbers

This technique is very useful, it is very simple, it can convert string data into numbers, but it is only suitable for String data, otherwise NaN will be returned, such as the following example:

function toNumber(strNumber) {
    return +strNumber;
}
console.log(toNumber("1234")); // 1234
console.log(toNumber("ACB")); // NaN

This also applies to Date, in this case, it will return the timestamp number:

console.log(+new Date()) // 1461288164385

And conditional character

If you have a piece of code like this:

if (conected) {
    login();
}

You can also abbreviate variables and use && to connect them with functions, such as the above example, you can The abbreviation is like this:

conected && login();

If some properties or functions exist in an object, you can also do this detection, as shown in the following code:

user && user.login();

Use || operation The symbol

has the feature of default parameters in ES6. To emulate this feature in older browsers, use the || operator and pass the default value as the second parameter. If the first parameter returns false, the second value will be considered a default value. Take the following example:

function User(name, age) {
    this.name = name || "Oliver Queen";
    this.age = age || 27;
}
var user1 = new User();
console.log(user1.name); // Oliver Queen
console.log(user1.age); // 27
var user2 = new User("Barry Allen", 25);
console.log(user2.name); // Barry Allen
console.log(user2.age); // 25

Cache array.length in a loop

This technique is very simple. This will have an impact on performance when processing a large array loop. will be very big. Basically, everyone will write an array that iterates synchronously like this:

for(var i = 0; i < array.length; i++) {
    console.log(array[i]);
}

If it is a small array, this is fine. If you are dealing with a large array, this code will iterate on each iteration. The size of the array will all be recalculated, which will cause some delays. In order to avoid this phenomenon, you can make a cache of array.length:

var length = array.length;
for(var i = 0; i < length; i++) {
    console.log(array[i]);
}

You can also write it like this:

for(var i = 0, length = array.length; i < length; i++) {
    console.log(array[i]);
}

Detect the attributes in the object

When you need This little trick is useful when checking the existence of some properties to avoid running undefined functions or properties. You might also want to use this trick if you plan to customize some cross-browser code. For example, you want to use document.querySelector() to select an id and make it compatible with the IE6 browser, but this function does not exist in the IE6 browser, so it is difficult to use this operator to detect whether the function exists. Very useful, as in the following example:

if (&#39;querySelector&#39; in document) {
    document.querySelector("#id");
} else {
    document.getElementById("id");
}

In this example, if the querySelector function does not exist in the document, then docuemnt.getElementById("id") will be called.

Get the last element in the array

Array.prototype.slice(begin,end) is used to get the array elements between begin and end. If you do not set the end parameter, the default length value of the array will be used as the end value. But some students may not know that this function can also accept negative values ​​as parameters. If you set a negative value as the value of begin, then you can get the last element of the array. For example:

var array = [1,2,3,4,5,6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]

Array truncation

This tip is mainly used to lock the size of the array. It is very useful if it is used to delete some elements in the array. . For example, your array has 10 elements, but you only want the first five elements, then you can truncate the array by array.length=5. As in the following example:

var array = [1,2,3,4,5,6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]

replaces all

String.replace()函数允许你使用字符串或正则表达式来替换字符串,本身这个函数只替换第一次出现的字符串,不过你可以使用正则表达多中的/g来模拟replaceAll()函数功能:

var string = "john john";
console.log(string.replace(/hn/, "ana")); // "joana john"
console.log(string.replace(/hn/g, "ana")); // "joana joana"

合并数组

如果你要合并两个数组,一般情况之下你都会使用Array.concat()函数:

var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.concat(array2)); // [1,2,3,4,5,6];

然后这个函数并不适合用来合并两个大型的数组,因为其将消耗大量的内存来存储新创建的数组。在这种情况之个,可以使用Array.pus().apply(arr1,arr2)来替代创建一个新数组。这种方法不是用来创建一个新的数组,其只是将第一个第二个数组合并在一起,同时减少内存的使用:

var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];

将NodeList转换成数组

如果你运行document.querySelectorAll(“p”)函数时,它可能返回DOM元素的数组,也就是NodeList对象。但这个对象不具有数组的函数功能,比如sort()、reduce()、map()、filter()等。为了让这些原生的数组函数功能也能用于其上面,需要将节点列表转换成数组。可以使用[].slice.call(elements)来实现:

var elements = document.querySelectorAll("p"); // NodeList
var arrayElements = [].slice.call(elements); // Now the NodeList is an array
var arrayElements = Array.from(elements); // This is another way of converting NodeList to Array

数组元素的洗牌

对于数组元素的洗牌,不需要使用任何外部的库,比如Lodash,只要这样做:

var list = [1,2,3];
console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]

转换数值的更加的方法

将字符串转换为数字是非常常见的。最简单和最快的(jspref)的方式来实现,将使用+(加)算法。 

var one = &#39;1&#39;;
var numberOne = +one; // Number 1

你也可以使用-(减号)算法的转换类型并且变成负数值。

var one = &#39;1&#39;;
var negativeNumberOne = -one; // Number -1

返回对象的函数能够用于链式操作

当创建面向对象的JavaScript对象的function时,函数返回一个对象将能够让函数可链式的写在一起来执行。   

function Person(name) {
this.name = name;
this.sayName = function() {
console.log("Hello my name is: ", this.name);
return this;
};
this.changeName = function(name) {
this.name = name;
return this;
};
}
var person = new Person("John");
person.sayName().changeName("Timmy").sayName();
//Hello my name is: John
//Hello my name is: Timmy

给回调函数传递参数   

在默认情况下,你无法将参数传给回调函数,如下:

function callback() {
console.log(&#39;Hi human&#39;);
}
document.getElementById(&#39;someelem&#39;).addEventListener(&#39;click&#39;, callback);

你可以采取JavaScript闭包的优点来给回调函数传参,案例如下:

function callback(a, b) {
return function() {
console.log(&#39;sum = &#39;, (a+b));
}
}
var x = 1, y = 2;
document.getElementById(&#39;someelem&#39;).addEventListener(&#39;click&#39;, callback(x, y));

什么是闭包呢?闭包是指一个针对独立的(自由)变量的函数。换句话说,闭包中定义的函数会记住它被创建的环境。了解更多请参阅MDN所以这种方式当被调用的时候,参数X/Y存在于回调函数的作用域内。

另一种方法是使用绑定方法。例如:

var alertText = function(text) {
alert(text);
};
document.getElementById(&#39;someelem&#39;).addEventListener(&#39;click&#39;, alertText.bind(this, &#39;hello&#39;));

提升

理解提升将帮助你组织你的function。只需要记住,变量声明和定义函数会被提升到顶部。变量的定义是不会的,即使你在同一行中声明和定义一个变量。此外,变量声明让系统知道变量存在,而定义是将其赋值给它。

function doTheThing() {
// 错误: notDeclared is not defined
console.log(notDeclared);
// 输出: undefined
console.log(definedLater);
var definedLater;
definedLater = &#39;I am defined!&#39;
// 输出: &#39;I am defined!&#39;
console.log(definedLater)
// Outputs: undefined
console.log(definedSimulateneously);
var definedSimulateneously = &#39;I am defined!&#39;
// 输出: &#39;I am defined!&#39;
console.log(definedSimulateneously)
// 输出: &#39;I did it!&#39;
doSomethingElse();
function doSomethingElse(){
console.log(&#39;I did it!&#39;);
}
// 错误: undefined is not a function
functionVar();
var functionVar = function(){
console.log(&#39;I did it!&#39;);
}
}

为了使事情更容易阅读,在函数作用域内提升变量的声明将会让你明确该变量的声明是来自哪个作用域。在你需要使用变量之前定义它们。在作用域底部定义函数,确保代码清晰规范。

希望这些小技巧能在工作中帮助你解决一些麻烦,对你有所帮助。

Statement
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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function