转载自: http://viralpatel.net/blogs/javascript-tips-tricks/
If you are doing lot of JavaScript programming, you might find below list of code snippets very useful. Keep it handy (bookmark it) and save it for future reference.
Here are 20 very useful JavaScript tips and tricks for you.
Disclaimer: Not all these snippet are written by me. Some of them are collected from other sources on Internet.
1. Converting JavaScript Array to CSV
First one goes like this. You have a javascript array of strings (or numbers) and you want to convert it to comma separated values (csv). We’ll below is the code snippet:
Reference: Array to CSV in JavaScript
var fruits = [ 'apple' , 'peaches' , 'oranges' , 'mangoes' ];
var str = fruits.valueOf();
//print str: apple,peaches,oranges,mangoes |
The valueOf()
method will convert an array in javascript to a comma separated string.
Now what if you want to use pipe (|) as delimeter instead of comma. You can convert a js array into a delimeted string using join()
method. See below:
var fruits = [ 'apple' , 'peaches' , 'oranges' , 'mangoes' ];
var str = fruits.join( "|" );
//print str: apple|peaches|oranges|mangoes |
The join()
method will convert the array into a pipe separated string.
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/1.html" frameborder="0" width="100%" height="200px"></iframe>
2. Convert CSV to Array in JavaScript
Now what if you want to convert a comma seprated string into a JavaScript array? We’ll there is a method for that too. You can use split()
method to split a string using any token (for instance comma) and create an array.
Reference: Array to CSV in JavaScript
In below example we split string str
on comma (,) and create a fruitsArray
array.
var str = "apple, peaches, oranges, mangoes" ;
var fruitsArray = str.split( "," );
//print fruitsArray[0]: apple |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/2.html" frameborder="0" width="100%" height="200px"></iframe>
3. Remove Array element by Index
You have an array. You want to remove a perticular element from array based on its index. We’ll you can do so using splice()
method. This method can add as well as removes element from an array. We will stick to its removal usage.
Reference: Remove element by array index
function removeByIndex(arr, index) {
arr.splice(index, 1);
} test = new Array();
test[0] = 'Apple' ;
test[1] = 'Ball' ;
test[2] = 'Cat' ;
test[3] = 'Dog' ;
alert( "Array before removing elements: " +test);
removeByIndex(test, 2); alert( "Array after removing elements: " +test);
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/3.html" frameborder="0" width="100%" height="200px"></iframe>
4. Remove Array element by Value
This one is very useful. You have an array and you want to remove an element based on its value (instead of index).
Reference: Remove element by array index
function removeByValue(arr, val) {
for ( var i=0; i<arr.length; i++) {
if (arr[i] == val) {
arr.splice(i, 1);
break ;
}
}
} var somearray = [ "mon" , "tue" , "wed" , "thur" ]
removeByValue(somearray, "tue" );
//somearray will now have "mon", "wed", "thur" |
See how in above code we defined a method removeByValue
that takes serves the purpose. In JavaScript you can define new functions to classes at runtime (although this is discourage) usingprototypes
.
In below code snippet, we create a new method removeByValue()
within Array
class. So now you can call this method as any other arrays method.
Array.prototype.removeByValue = function (val) {
for ( var i=0; i< this .length; i++) {
if ( this [i] == val) {
this .splice(i, 1);
break ;
}
}
} //.. var somearray = [ "mon" , "tue" , "wed" , "thur" ]
somearray.removeByValue( "tue" );
//somearray will now have "mon", "wed", "thur" |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/4.html" frameborder="0" width="100%" height="200px"></iframe>
5. Calling JavaScript function from String
Sometime you want to call a Javascript method at runtime whos name you know. Let say there is a method “foo()” which you want to call at runtime. Below is a small JS snippet that helps you calling a method just by its name.
Reference: Call Function as String
var strFun = "someFunction" ; //Name of the function to be called
var strParam = "this is the parameter" ; //Parameters to be passed in function
//Create the function var fn = window[strFun];
//Call the function fn(strParam); |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/5.html" frameborder="0" width="100%" height="200px"></iframe>
6. Generate Random number from 1 to N
Below little snippet helps you in generating random number between 1 to N. Might come handy for your next JS game.
//random number from 1 to N var random = Math.floor(Math.random() * N + 1);
//random number from 1 to 10 var random = Math.floor(Math.random() * 10 + 1);
//random number from 1 to 100 var random = Math.floor(Math.random() * 100 + 1);
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/6.html" frameborder="0" width="100%" height="200px"></iframe>
7. Capture browser close button event or exiting the page in JavaScript
This is a common use case. You want to capture the browsers close event so that you can alert user if there is any unsaved data on webpage that should be saved. Below javascript snippet will help you in that.
Reference: Capture Browser Close Event
<script language= "javascript" >
function fnUnloadHandler() {
// Add your code here
alert( "Unload event.. Do something to invalidate users session.." );
} </script> <body onbeforeunload= "fnUnloadHandler()" >
<!-- Your page content -->
</body> |
8. Warn user if Back is pressed
This is same as above. Difference is instead of capturing close event here we capture back button event. So that we know if user is moving awaw from this webpage.
Reference: Capture Browser Back Button
window.onbeforeunload = function () {
return "You work will be lost." ;
}; |
9. Check if Form is Dirty
A common usecase. You need to check if user changed anything in an HTML form. Below functionformIsDirty
returns a boolean value true or false depending on weather user modified something within the form.
/** * Determines if a form is dirty by comparing the current value of each element
* with its default value.
*
* @param {Form} form the form to be checked.
* @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>
* otherwise.
*/
function formIsDirty(form) {
for ( var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio" ) {
if (element.checked != element.defaultChecked) {
return true ;
}
}
else if (type == "hidden" || type == "password" ||
type == "text" || type == "textarea" ) {
if (element.value != element.defaultValue) {
return true ;
}
}
else if (type == "select-one" || type == "select-multiple" ) {
for ( var j = 0; j < element.options.length; j++) {
if (element.options[j].selected !=
element.options[j].defaultSelected) {
return true ;
}
}
}
}
return false ;
} |
window.onbeforeunload = function (e) {
e = e || window.event;
if (formIsDirty(document.forms[ "someForm" ])) {
// For IE and Firefox
if (e) {
e.returnValue = "You have unsaved changes." ;
}
// For Safari
return "You have unsaved changes." ;
}
}; |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/8.html" frameborder="0" width="100%" height="200px"></iframe>
10. Disable Back button using JavaScript
This one is tricky. You want to disable the browsers back button (Dont ask me why!!). Below code snippet will let you do this. The only catch here is that you need to put this code in page where you dont want user to come back. See below reference for more details.
Reference: Disable Browsers Back Button
<SCRIPT type= "text/javascript" >
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT> </HEAD> <BODY onload= "noBack();"
onpageshow= "if (event.persisted) noBack();" onunload= "" >
|
11. Deleting Multiple Values From Listbox in JavaScript
You have a SELECT box. User can select multiple OPTIONS from this SELECT box and remove them. Below Javascript function selectBoxRemove
let you do this. Just pass ID of SELECT object you want to remove OPTIONS in.
Reference: Delete Multiple Options in Select
function selectBoxRemove(sourceID) {
//get the listbox object from id.
var src = document.getElementById(sourceID);
//iterate through each option of the listbox
for ( var count= src.options.length-1; count >= 0; count--) {
//if the option is selected, delete the option
if (src.options[count].selected == true ) {
try {
src.remove(count, null );
} catch (error) {
src.remove(count);
}
}
}
} |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/11.html" frameborder="0" width="100%" height="260px"></iframe>
12. Listbox Select All/Deselect All using JavaScript
You can use below JS snippet to select/deselect all the OPTIONS from a SELECT box. Just pass the ID of select box you want to perform this operation on and also a boolean value isSelect
specifying what operation you want to perform.
Reference: Select All/None using Javascript
function listboxSelectDeselect(listID, isSelect) {
var listbox = document.getElementById(listID);
for ( var count=0; count < listbox.options.length; count++) {
listbox.options[count].selected = isSelect;
}
} |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/12.html" frameborder="0" width="100%" height="270px"></iframe>
13. Listbox Move selected items Up / Down
This one is useful if you are playing a lot with multi options select box in your application. This function let you move select OPTIONS in a SELECT box to UP or DOWN. See below reference for more details.
Reference: Move Up/Down Selected Items in a Listbox
function listbox_move(listID, direction) {
var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;
if (-1 == selIndex) {
alert( "Please select an option to move." );
return ;
}
var increment = -1;
if (direction == 'up' )
increment = -1;
else
increment = 1;
if ((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return ;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.selectedIndex = selIndex + increment;
} //.. //.. listbox_move( 'countryList' , 'up' ); //move up the selected option
listbox_move( 'countryList' , 'down' ); //move down the selected option
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/13.html" frameborder="0" width="100%" height="260px"></iframe>
14. Listbox Move Left/Right Options
This javascript function lets you move selected OPTIONS between two SELECT boxes. Check below reference for details.
Reference: Move Options Left/Right between two SELECT boxes
function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
for ( var count=0; count < src.options.length; count++) {
if (src.options[count].selected == true ) {
var option = src.options[count];
var newOption = document.createElement( "option" );
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true ;
try {
dest.add(newOption, null ); //Standard
src.remove(count, null );
} catch (error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
}
}
} //.. //.. listbox_moveacross( 'countryList' , 'selectedCountryList' );
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/14.html" frameborder="0" width="100%" height="260px"></iframe>
15. Initialize JavaScript Array with series of numbers
Sometime you want to initialize a Javascript array with series of numbers. Below code snippet will let you achieve this. This will initialiaze array numbers
with numbers 1 to 100.
var numbers = [];
for ( var i=1; numbers.push(i++)<100;);
//numbers = [0,1,2,3 ... 100] |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/15.html" frameborder="0" width="100%" height="200px"></iframe>
16. Rounding Numbers to ‘N’ Decimals
This one is quite useful. It will let you round off a number to ‘N’ decimal places. Here in below example we are rounding of a number to 2 decimal places.
var num = 2.443242342;
alert(num.toFixed(2)); // 2.44
|
Note that we use toFixed()
method here. toFixed(n)
provides n length after the decimal point; whereastoPrecision(x)
provides x total length.
num = 500.2349; result = num.toPrecision(4); // result will equal 500.2
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/16.html" frameborder="0" width="100%" height="200px"></iframe>
17. Check if String contains another substring in JavaScript
Below code snippet (courtesy Stackoverflow) let you check if a given string contains another substring.
Reference: stackoverflow
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, start) {
for ( var i = (start || 0), j = this .length; i < j; i++) {
if ( this [i] === obj) { return i; }
}
return -1;
}
} if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~ this .indexOf(arg);
};
} |
The code will add two new methods to String, indexOf
and contains
. Once this is done, you can use contains method to check weather a substring is present in a given string.
var hay = "a quick brown fox jumps over lazy dog";
var needle = "jumps";
alert(hay.contains(needle));
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/17.html" frameborder="0" width="100%" height="200px"></iframe>
18. Remove Duplicates from JavaScript Array
Aha!! You know this one comes quite handy. Just call removeDuplicates method and pass the array, it should remove all duplicate elements from the array.
function removeDuplicates(arr) {
var temp = {};
for ( var i = 0; i < arr.length; i++)
temp[arr[i]] = true ;
var r = [];
for ( var k in temp)
r.push(k);
return r;
} //Usage var fruits = [ 'apple' , 'orange' , 'peach' , 'apple' , 'strawberry' , 'orange' ];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry']; |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/18.html" frameborder="0" width="100%" height="200px"></iframe>
19. Trim a String in JavaScript
Below code will add a method trim() to String which can be used to remove spaces from both sides of a string.
if (!String.prototype.trim) {
String.prototype.trim= function () {
return this .replace(/^\s+|\s+$/g, '' );
};
} //usage var str = " some string " ;
str.trim(); //print str = "some string" |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/19.html" frameborder="0" width="100%" height="200px"></iframe>
20. Redirect webpage in JavaScript
This javascript code should perform http redirect on a given URL.
window.location.href = "http://viralpatel.net" ;
|
21. Encode a URL in JavaScript
Whenever you are making an http request and passing some parameters. You should encode the URL string. Use encodeURIComponent function for encoding a url parameter.
Reference: w3scools
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/21.html" frameborder="0" width="100%" height="200px"></iframe>
相关推荐
闭包是JavaScript的一个重要特性,它可以访问并操作函数内部变量,即使函数已经执行完毕。通过学习和实践这些实例,你可以理解如何有效利用闭包来实现数据封装和持久化存储。 2. **原型与继承** JavaScript的原型...
"JavaScript经典实例"这个主题涵盖了一系列经过实践验证的代码片段和实用技巧,旨在帮助开发者深化对JavaScript的理解并提升技能。 描述中提到“内容丰富”,意味着这个压缩包可能包含了各种类型的JavaScript应用...
这个“300个JavaScript应用实例”集合提供了一系列实用的代码片段,旨在帮助开发者深入理解和掌握JavaScript的核心概念及实际运用技巧。 1. **基础语法** JavaScript的基础包括变量、数据类型(如字符串、数字、...
"超实用的javascript代码段"是席新亮著作的一个资源集合,提供了许多实际开发中常用且高效的代码片段,对于学习和提升JavaScript编程技能非常有帮助。 一、基础语法与类型 JavaScript的基础语法包括变量声明(var、...
全书共分10篇,主要包括JavaScript的时间日期类、文本、鼠标、图片、页面等特效、页面技巧与页面游戏、导航菜单、Cookie和JavaScript的综合技巧等方面,涉及了JavaScript的网络应用的绝大部分内容。针对每个实例给出...
JavaScript是一种用于开发Internet客户端应用的基于事件的脚本语言,它也是一套与超文本标记语言HTML紧密结合的脚本语言,为网页制作者提供了非常灵活的应用和发挥空间。 本书用详尽的实例全面介绍了使用...
"javaScript特效实例+技巧"这个主题涵盖了JavaScript在实际开发中的各种实用技巧和效果实现,对于提升前端开发效率具有重要作用。 1. **JavaScript特效实例**: - JavaScript特效包括但不限于:滑动菜单、轮播图、...
这个压缩包包含大约400个JavaScript实例,是学习和理解JavaScript功能与应用的宝贵资源。下面,我们将深入探讨JavaScript的一些核心知识点,以及如何利用这些实例进行学习。 1. **变量和数据类型**:JavaScript支持...
这个压缩包包含了一系列关于JavaScript的经典实例,旨在帮助用户深入理解和掌握这门语言的各种实用技巧。 首先,"JavaScript经典实例.docx"提供了7页的案例,可能涵盖了JavaScript的基础语法、函数、变量、条件语句...
在"JavaScript经典实例教程代码"这个资源中,你将找到一系列实用的代码示例,帮助你深入理解和掌握JavaScript的核心概念及应用技巧。 1. **基础语法**:JavaScript的基础包括变量声明、数据类型(如字符串、数字、...
本资料包“JavaScript小特效实例”汇聚了多个常见的JavaScript特效,包括页面特效、鼠标特效以及文本框特效等,旨在帮助开发者或学习者掌握并应用这些实用技巧。 1. **页面特效**:页面特效通常涉及页面元素的动画...
"JavaScript经典实例"聚焦于展示JavaScript在实际应用中的各种实用技巧和常见问题的解决方案。 这本书涵盖了20类不同的JavaScript主题,总计343个经典实例,旨在帮助开发者深入理解并熟练掌握JavaScript的使用。...
总的来说,"JavaScript486实例包含源文件"是一个非常实用的学习资源,无论你是初入编程的新手还是寻求提升的老兵,都能从中受益匪浅。通过深入学习和实践这些实例,你不仅可以巩固基础,还能提升解决实际问题的能力...
这个压缩包“JavaScript实例大全”显然是一份集合了多种JavaScript相关资源的宝典,包括“JavaScript网页设计300例”、“javascript源码大全”以及“jquery 1.7 中文 api 修正版”。 首先,“JavaScript网页设计300...
在“javascript经典网页实例”这个主题中,我们可以深入探讨JavaScript在前台网页开发中的重要作用及其各种实用技巧。 首先,JavaScript是浏览器支持的语言,它使得网页能够实时更新、验证用户输入、响应用户交互,...
本篇将深入探讨JavaScript实例应用,涵盖其基本语法、常见操作以及一些实用技巧。 1. **基本语法** JavaScript的基础包括变量声明(`var`, `let`, `const`)、数据类型(如字符串、数字、布尔值、数组、对象等)、...
在JavaScript编程中,这些实用代码实例展示了如何利用JS来增强网页的交互性和功能。下面将逐一解析这些知识点: 1. **可视窗口的背景着色**: 通过CSS样式设置`body`元素的`background-color`属性,可以改变浏览器...
"JavaScript常用特效实例"这个主题涵盖了JavaScript在网页设计中的多种实用技巧和效果,下面将详细介绍其中可能涉及的一些关键知识点。 1. **DOM操作**:JavaScript能够通过Document Object Model(DOM)来改变HTML...
这个"JavaScript网页特效实例"的主题,显然聚焦于利用JavaScript技术来创建吸引用户注意力、增强用户体验的视觉特效。以下是一些相关的JavaScript网页特效及其背后的原理和实践技巧。 1. **页面加载动画**:在网页...