21 Javas Tips Worth Collecting

Source: Internet
Author: User
Tags string back javascript array

In this article are listed 21 worthy of the collection of JavaScript skills, in the actual work, if appropriate to use, then greatly improve work efficiency.

1 JavaScript arrays converted to CSV format

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

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

Output: Apple,peaches,oranges,mangoes

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

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

Output: Apple|peaches|oranges|mangoes

2 convert CSV format back to javscript array

So how do you turn a CSV-formatted string back into a JavaScript array? Using the Split () method, you can use any of the specified characters to separate the code as follows:

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

Output FRUITSARRAY[0]: Apple

3 to move an element in an array by 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 parameter n, to move the divisor group.

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 last output is Apple,ball,dog

4 to remove values from 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:

function Removebyvalue (arr, Val) {for (Var i=0; i

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

Array.prototype.removeByValue = function (val) {for (Var i=0; i

5 calling a method dynamically in a string-specified manner

Sometimes, you need to invoke an existing method dynamically at run time, and pass in parameters for it. How can this be achieved? The following code can:

var strfun = "SomeFunction"; SomeFunction for the method name already defined var strparam = "This is the parameter"; The parameter to pass in the method var fn = Window[strfun]; Call method passed in parameter FN (strparam);

6 generating random numbers from 1 to n

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-closed events

We often hope that when the user closes the browser, prompting the user to save something that has not yet been saved, the following JavaScript technique is very useful, the code is as follows:

.........

is to write the code for the onBeforeUnload () event

8 Check if the fallback key is pressed

Again, you can check to see if the user pressed the fallback key, as shown in the following code:

Window.onbeforeunload = function () {return "You work would be lost.";};

9 Check if the form data changes

Sometimes, when you need to check whether a user has modified the contents of a form, you can use the following technique, 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:

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 (Ty PE = = "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.O ptions[j].defaultselected) {return true;}} }} return false; } window.onbeforeunload = function (e) {e = e | | window.event; if (Formisdirty (document.forms["Someform"]) {//IE and Fire Fox if (e) {e.returnvalue = "you have unsaved changes.";}//Safari browser return "You have unsaved changes."; } };

10 completely disable the use of the back key

The following tips are placed on the page, which prevents the user from clicking the back key, which in some cases is required. The code is as follows:

  

11 Delete the item selected in the user's multi-box

The following tips are available when the user is selecting multiple items in the dropdown box, when the point is deleted, they can be deleted at once, the code is as follows:

function Selectboxremove (SourceID) {//Get the ID of the listbox var src = document.getElementById (SourceID);//Loop listbox for (Var Count= src.options.length-1; Count >= 0; count--) {//If the option to delete is found, delete if (src.options[count].selected = = True) {try {src.remove (count, null);} catch (Error) {src. Remove (count); } } } }

Full and non-full selection in the listbox

In the case of a specified ListBox, the following method can pass in true or false, depending on the user's needs, representing all or not all items in the ListBox, with the following code:

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

13 Move up and down items in the listbox

The following code gives a list of how to move items up and down in a ListBox

Unction Listbox_move (ListID, direction) {var listbox = document.getElementById (ListID); var selindex = Listbox.selectedi Ndex; 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 a project in two different listbox

If in two different listbox it is often necessary to move an item in a ListBox on the left to another listbox, here is the relevant code:

function Listbox_moveacross (SourceID, DestID) {var src = document.getElementById (SourceID); var dest = Document.geteleme Ntbyid (DestID); for (var count=0; count < src.options.length; count++) {if (src.options[count].selected = = true) {var option = Src.opti Ons[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, with the following code:

var numbers = []; for (var I=1; Numbers.push (i++) <100;)//numbers = [0,1,2,3 ... 100] Using the push method of the array

16 truncation of decimal places for a specified number of digits

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

var num = 2.443242342; Alert (num.tofixed (2));  2.44 and using toprecision (x) provides the precision of the specified number of digits, where x is the total number of digits, such as num = 500.2349; result = Num.toprecision (4);//Output 500.2

17 Check if string contains other strings

In the following code, you can implement checking whether a string contains other strings. The code is 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); }; }

In the above code, the IndexOf method is overridden and the Contains method is defined, using the following method:

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

18 removing duplicate elements from the Javscript array

The following code removes the duplicate elements from the JavaScript array, as follows:

function RemoveDuplicates (arr) {var temp = {}; for (var i = 0; i < arr.length; i++) Temp[arr[i]] = true; var r = []; f or (var k in temp) R.push (k); return R; }//usage var fruits = [' apple ', ' orange ', ' peach ', ' apple ', ' strawberry ', ' orange ']; var uniquefruits = removeduplicates (fruits); Output of the uniquefruits [' Apple ', ' orange ', ' peach ', ' strawberry '];

19 Remove the extra spaces in the string

The following code adds a trim () method to string, with the following code:

if (! String.prototype.trim) {string.prototype.trim=function () {return this.replace (/^\s+|\s+$/g, ');};}//usage var str = "s ome string "; Str.trim (); Output str = "some string"

REDIRECT in JavaScript

In JavaScript, you can implement redirects in the following ways:

Window.location.href = "Http://viralpatel.net";

21 Encoding a URL

Sometimes, you need to encode the pass-through in the URL as follows:

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

21 Javas Tips Worth Collecting

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.