Home Web Front-end JS Tutorial 10 JavaScript tricks you may not know

10 JavaScript tricks you may not know

Nov 26, 2016 am 09:30 AM
javascript

1. Variable conversion
It seems very simple, but from what I have seen, using constructors, like Array() or Number() to perform variable conversion is a common practice. Always use primitive data types (sometimes called literals) to convert variables, which has no additional impact but is more efficient.
var myVar = "3.14159",
str = ""+ myVar,// to string
int = ~~myVar, // to integer
float = 1*myVar, // to float
bool = !!myVar, / * to boolean - any string with length
and any number except 0 are true */
array = [myVar]; // to array
convert date (new Date(myVar)) and regular expression (new RegExp(myVar)) The constructor must be used, and the /pattern/flags format must be used when creating a regular expression.

2. Convert decimal to hexadecimal or octal, or vice versa
Can you write a separate function to convert hexadecimal (or octal)? Stop it now! There are easier ready-made functions available:
(int).toString(16); // converts int to hex, eg 12 => "C"
(int).toString(8); // converts int to octal, eg. 12 => "14"
parseInt(string,16) // converts hex to int, eg. "FF" => 255
parseInt(string,8) // converts octal to int, eg. "20" => 16
3. Play with numbers
In addition to the ones introduced in the previous section, here are more tips for processing numbers
0xFF; // Hex declaration, returns 255
020; // Octal declaration, returns 16
1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000
(1000).toExponential(); // Opposite with previous, returns 1e3
(3.1415).toFixed(3) ; // Rounding the number, returns "3.142"
4.Javascript version detection
Do you know which version of Javascript your browser supports? If you don't know, go to Wikipedia and check the Javascript version table. For some reason, some features of Javascript 1.7 are not widely supported. However, most browsers support the features of versions 1.8 and 1.8.1. (Note: All IE browsers (IE8 or older) only support Javascript version 1.5) Here is a script that can not only detect the JavaScript version by detecting features, but also check the features supported by a specific Javascript version .
var JS_ver = [];
(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf && [].forEach)?JS_ver.push("1.6"):false ;
((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"): false;
([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;
("".trimLeft)?JS_ver.push("1.8.1"):false;
JS_ver.supports = function()
{
 if (arguments[0])
  return (!!~this.join().indexOf(arguments[0] +",") +",");
 else
  return (this[this.length-1]);
}
alert("Latest Javascript version supported: "+ JS_ver.supports());
alert("Support for version 1.7 : "+ JS_ver.supports("1.7") );
5. Use window.name for simple session processing
This is something I really like. You can specify a string as the value of the window.name property until you close the tab or window. Although I haven't provided any scripts, I highly recommend that you take advantage of this method. For example, when building a website or application, it is very useful to switch between debug and test mode.
6. Determine whether the attribute exists
This problem includes two aspects, not only checking the existence of the attribute, but also getting the type of the attribute. But we always overlook these little things:
// BAD: This will cause an error in code when foo is undefined
if (foo) {
 doSomething();
}
// GOOD: This doesn't cause any errors. However, even when
// foo is set to NULL or false, the condition validates as true
if (typeof foo != "undefined") {
 doSomething();
}
// BETTER: This doesn't cause any errors and in addition
// values ​​NULL or false won't validate as true
if (window.foo) {
 doSomething();
}
However, there are cases where we have deeper structures and need more The appropriate check can be like this:
// UGLY: we have to proof existence of every
// object before we can be sure property actually exists
if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
 doSomething();
}
7. Pass parameters to the function
When the function has both required and optional parameters, we may do this:
function doSomething(arg0, arg1, arg2, arg3, arg4 ) {
 ...
}
doSomething('', 'foo', 5, [], false);
And passing an object is always more convenient than passing a bunch of parameters:
function doSomething() {
// Leaves the function if nothing is passed
 if (!arguments[0]) {
 return false;
 }
 var oArgs = arguments[0]
 arg0 = oArgs.arg0 || "",
 arg1 = oArgs.arg1 || "",
 arg2 = oArgs.arg2 || 0,
arg3 = oArgs.arg3 || [],
arg4 = oArgs.arg4 || false;
}
doSomething({
arg1 : "foo",
arg2 : 5,
 arg4 : false
});
This is just a very simple example of passing an object as a parameter. For example, we can also declare an object, with the variable name as Key and the default value as Value.
8.Use document.createDocumentFragment()
You may need to append multiple elements to the document dynamically. However, inserting them directly into the document will cause the document to need to be re-layouted each time. Instead, you should use document fragments and only append once after completion:
function createList() {
 var aLI = ["first item ", "second item", "third item",
 "fourth item", "fith item"];
  // Creates the fragment
 var oFrag = document.createDocumentFragment();
 while (aLI.length) {
  var oLI = document.createElement("li");
   // Removes the first item from array and appends it
   // as a text node to LI element
   oLI.appendChild(document.createTextNode(aLI.shift()));
  oFrag.appendChild(oLI);
 }
 document.getElementById('myUL').appendChild(oFrag);
}
9. Pass a function to the replace() method
Sometimes you want to replace a certain part of the string For other values, the best way is to pass a separate function to String.replace(). Here is a simple example:
var sFlop = "Flop: [Ah] [Ks] [7c]";
var aValues ​​= {"A":"Ace","K":"King",7:"Seven" };
var aSuits = {"h":"Hearts","s":"Spades",
"d":"Diamonds","c":"Clubs"};
sFlop = sFlop.replace(/[ w+]/gi, function(match) {
 match = match.replace(match[2], aSuits[match[2]]);
match = match.replace(match[1], aValues[match[1]] +" of ");
 return match;
});
// string sFlop now contains:
// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"
10. Label in loop Use www.2cto.com
Sometimes, there are loops nested in the loop. You may want to exit in the loop, you can use the tag:
outerloop:
for (var iI=0;iI<5;iI++) {
 if (somethingIsTrue()) {
  // Breaks the outer loop iteration
 break outerloop;
 }
 innerloop:
 for (var iA=0;iA<5;iA++) {
  if (somethingElseIsTrue()) {
// Breaks the inner loop iteration
  break innerloop;
 }
 }
}

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)

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