search
HomeWeb Front-endJS Tutorial10 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 if (somethingIsTrue()) {
  // Breaks the outer loop iteration
 break outerloop;
 }
 innerloop:
 for (var iA=0;iA  if (somethingElseIsTrue()) {
// Breaks the inner loop iteration
  break innerloop;
 }
 }
}

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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use