21 favorite JavaScript Tips _javascript Tips

Source: Internet
Author: User
Tags string back javascript array

1 JavaScript array converted to CSV format

Consider the following scenario first, with a javscript character (or numeric) array that now needs to be converted to a comma-separated CSV format file. Then we can use the following tips, the code is as follows:

Copy Code code as follows:

var fruits = [' apple ', ' Peaches ', ' oranges ', ' mangoes '];
var str = fruits.valueof ();

Output: Apple,peaches,oranges,mangoes

where the valueof () method converts a JavaScript array into a comma-separated string. Note that if you want to not use a comma split, such as a | number split, use the Join method, as follows:

Copy Code code as follows:

var fruits = [' apple ', ' Peaches ', ' oranges ', ' mangoes '];
var str = fruits.join ("|");

Output: Apple|peaches|oranges|mangoes

2 re-converting CSV format back to javscript array

So how do you turn a CSV-formatted string back into a JavaScript array? You can use the split () method to delimit any of the characters you specify, and the code is as follows:

Copy Code code as follows:

var str = "Apple, peaches, oranges, mangoes";
var Fruitsarray = Str.split (",");

Output FRUITSARRAY[0]: Apple

3 Move an element in an array according to the index

If you need to remove an element from a JavaScript array, you can use the Splice method, which will remove the nth element (from the No. 0 bit in the JavaScript array), based on the incoming argument n, to move the divisor group.

Copy Code code as follows:

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);

Then the final output is Apple,ball,dog

 4 to move the value in an array element based on the value of the element

The following technique is useful for removing elements from an array based on a given value, as follows:

Copy Code code as follows:

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");
The elements that Somearray will have are "mon", "Wed", "Thur"

Of course, the better way is to use the prototype method to implement the following code:

Copy Code code as follows:

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");

5 dynamic invocation of a method in a way specified by a string

Sometimes, you need to call an existing method dynamically at run time and pass in the parameters for it. How does this happen? The following code can:

Copy Code code as follows:

var strfun = "SomeFunction"; SomeFunction for a method name that has already been defined
var strparam = "This is the parameter"; Parameters to pass in the method
var fn = Window[strfun];

Calling method passing Parameters
FN (strparam);

6 random numbers that generate 1 to n

Copy Code code as follows:

var random = Math.floor (Math.random () * N + 1);
Generates a random number from 1 to 10
var random = Math.floor (Math.random () * 10 + 1);
Generates a random number from 1 to 100
var random = Math.floor (math.random () * 100 + 1);

7 Capturing browser shutdown events

We often hope that when the user closes the browser and prompts the user to save what has not been saved, the following JavaScript technique is useful, as follows:

Copy Code code as follows:

<script language= "JavaScript" >
function Fnunloadhandler () {

Alert ("Unload event.") Do something to invalidate users session ... ");
}
</script>
<body onbeforeunload= "Fnunloadhandler ()" >
.........
</body>

is to write the code for the onBeforeUnload () event

8 Check to see if the fallback key is pressed

Similarly, you can check if the user has pressed the rollback key, as follows:

Copy Code code as follows:

Window.onbeforeunload = function () {
Return ' You work'll be lost. '
};

  9 Check that the form data is changed

Sometimes, you need to check to see if the user has modified the contents of a form, you can use the following tips, which returns true if the contents of the form are modified, and False if the contents of the form are not modified. The code is as follows:

Copy Code code as follows:

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"])) {
IE and Firefox
if (e) {
E.returnvalue = "You have unsaved changes."
}
Safari Browser
Return "have unsaved changes."
}
};


  10 completely prohibit the use of the back key

The following tips are placed on the page to prevent the user from clicking Back, which in some cases is required. The code is as follows:

Copy Code code as follows:

<script type= "Text/javascript" >
Window.history.forward ();
function Noback () {Window.history.forward ();}
</SCRIPT>
</HEAD>
<body onload= "Noback ();"
Onpageshow= "if (event.persisted) noback ();" Onunload= "" >

  11 Delete items selected in the user's multiple selection box

The technique below is that when the user chooses items in the dropdown box, when the point is deleted, you can delete them at once, the code is as follows:

Copy Code code as follows:

function Selectboxremove (SourceID) {
Get the ID of the listbox
var src = document.getElementById (SourceID);

Circular ListBox
for (var count= src.options.length-1; count >= 0; count--) {

If you find the option you want to delete, delete the
if (src.options[count].selected = = True) {

try {
Src.remove (count, null);

catch (Error) {

Src.remove (count);
}
}
}
}

Full selection and non-total selection in the listbox

If you have a specified ListBox, the following method can pass in true or false, depending on the needs of the user, representing all items in the Select ListBox or all items that are not all selected, as follows:

Copy Code code as follows:

function Listboxselectdeselect (Listid, Isselect) {
var listbox = document.getElementById (Listid);
for (var count=0; count < listbox.options.length; count++) {
listbox.options[count].selected = Isselect;
}
}

 13 moving up and down in the listbox

The following code shows how to move items up and down in a ListBox

Copy Code code as follows:

function Listbox_move (Listid, direction) {

var listbox = document.getElementById (Listid);
var selindex = Listbox.selectedindex;

if ( -1 = Selindex) {
Alert ("Please select a 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

  14 moving items in two different listbox

If you are in two different ListBox, you often need to move the item to another listbox in a ListBox on the left, and here's the code:

Copy Code code as follows:

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 ');

 15 fast initialization of javscript arrays

The following method gives a quick way to initialize a javscript array, the following code:

Copy Code code as follows:

var numbers = [];
for (Var i=1 numbers.push (i++) <100;);
numbers = [0,1,2,3 ... 100]

Using the push method of the array

  16 Intercept the decimal number of the specified digits

If you want to intercept a specified number of digits after a decimal, you can use the Tofixed method, such as:

Copy Code code as follows:

var num = 2.443242342;
Alert (num.tofixed (2));

Using Toprecision (x) provides the precision of the specified number of digits, where x is the total number of digits, such as:

Copy Code code as follows:

num = 500.2349;
result = Num.toprecision (4); Output 500.2

  17 Check if the string contains other strings

The following code enables you to check whether a string contains other strings. The code is as follows:

Copy Code code as follows:

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 IndexOf method is overridden in the above code and the Contains method is defined, using the following method:

Copy Code code as follows:

var hay = "A quick brown fox jumps over lazy dog";
var needle = "jumps";
Alert (Hay.contains (needle));

  18 remove the repeating element from the Javscript array

The following code can remove the repeating element from the JavaScript array as follows:

Copy Code code as follows:

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);
Output uniquefruits [' Apple ', ' orange ', ' peach ', ' strawberry '];

 19 Remove extra space in string

The following code adds an trim () method for string, as follows:

Copy Code code as follows:

if (! String.prototype.trim) {
String.prototype.trim=function () {
Return This.replace (/^\s+|\s+$/g, "");
};
}

Usage
var str = "some string";
Str.trim ();
Output str = "some string"

  REDIRECT in JavaScript

In JavaScript, you can implement redirects by following these methods:

Copy Code code as follows:

Window.location.href = "Http://www.jb51.net";


   21 encoding the URL

Sometimes, you need to encode the passes in the URL as follows:

Copy Code code as follows:

var myotherurl = "Http://example.com/index.html?url=" + encodeuricomponent (Myurl);

Original: http://viralpatel.net/blogs/javascript-tips-tricks/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.