Home > Article > Web Front-end > 10 JavaScript tricks you may not know
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;
}
}
}