1 JavaScript array convert to CSV format
First of all, consider the following application scenarios. There is a character type (or numerical) array of Javscript. Now you need to convert it to a comma -divided 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
Among them, the valueof () method will transform the JavaScript array into a strings separated by comma. It should be noted that if you do n’t want to use a comma segment, such as | No. divide, please use the job 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 -convert the CSV format back to the Javscript array
So how to transform a CSV format back to the JavaScript array? You can use the split () method to separate the specified character. The code is as follows:
Copy code code as follows:
var str = "Apple, Peaches, Orange, mangoes";
var fruitsarray = str.split (",");
Output Fruitsarray [0]: Apple
3 According to the index shift, a certain element in the array
If you need to remove a certain element from the JavaScript array, you can use the Splice method. This method will be removed from the NAScript array from the 0th place in the array) according to the passing parameter N).
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);
The final output is Apple, Ball, DOG
4 Depending on the value of the element to remove the value in the array element
The following techniques are very practical. Delete the elements in the array based on the given value. The code is 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, "");
// SomeARAY will have the elements of "Mon", "WED", "Thur"
Of course, a better way is to achieve the method of using the prototype, as follows: the following code:
Copy code code as follows:
Array.prototype.removebyValue = Function (Val) {
for (var I = 0; I <THIS.Length; I ++) {
if (this [i] == value) {
this.splice (i, 1);
Break;
}
}
}
// ..
var somearray = ["mon", "tue", "wed", "thur"]
somearray.removebyvalue ("tue");
5 Dynamically call a method by specified by a string
Sometimes, when running, you need to dynamically call an existing method and pass the parameters for it. How to achieve this? The following code can be:
Copy code code as follows:
Var StrFun = "SOMEFUNCTION"; // Somefunction is a defined method name
var strparam = "this is the parameter"; // to pass the parameters of the method
var fn = window [strfun];
// The call method is passed into parameters
fn (strparam);
6 generate 1 to N random numbers
Copy code code as follows:
var random = math.floor (math.random () * n + 1);
// Generate random numbers between 1 and 10
var random = math.floor (math.random () * 10 + 1);
// Generate random numbers between 1 and 100
var random = math.floor (math.random () * 100 + 1);
7 Capture the browser closure event
We often hope that when the user closes the browser, it prompts the user to save what has not been preserved. The following JavaScript skills are very useful. The code is as follows:
Copy code code as follows:
<script language = "javascript">
Function Fnunloadhandler () {
alert ("unload event .. do something to invalidate uters session ..");
}
</script>
<body onbeForeunload = "Fnunloadhandler ()">
... ...
</body>
Just write the code of the onbeForeunload () event
8 Check if you press the back key
Similarly, you can check whether the user presses the back key, the code is as follows:
Copy code code as follows:
Window.onbeForeunload = Function () {
Return "you work will be lost.";
};
9 Check whether the form data changes
Sometimes, if you need to check whether the user modifies the content in a form, you can use the following techniques. Among them, if the content of the form is modified, it returns true and the content of the form is returned to FALSE. The code is as follows:
Copy code code as follows:
Function formisDiRTY (FORM) {
for (var I = 0; I <FORM.ELEMENTS.Length; I ++) {
varing = form.elements [i];
var Type = Element.type;
if (Type == "Checkbox" || Type == "Radio") {{
If (Element.check! = 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] .select! =
element.options [j] .defaultSelect) {{
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 "you have unsaved changes.";
}
};
10 completely prohibited from using the back key
The following techniques are placed on the page, which can prevent users from pointing back and back keys, which is needed in some cases. The code is as follows:
Copy code code as follows:
<Script type = "text/javascript">
window.history.Forward ();
function not () {window.history.forward ();}
</Script>
</Head>
<Body only = "not ();"
OnPageShow = "IF (Event.persisisted) Noback ();" onunload = "">>
11 Delete the project selected in multiple choice boxes
The technique provided below is that when the user is selected by multiple projects in the drop -down box, when the point is deleted, you can delete them at one time. The code is as follows:
Copy code code as follows:
Function Selectboxremove (Sourceid) {{
// Get the IDBOX ID
var src = document.getelementByid (sourceid);
// Cycle Listbox
for (var count = src.options.length-1; count> = 0; count-) {
// If you find the option to be deleted, delete it
if (src.options [count] .select == true) {
try {
src.remove (count, null);
} Catch (error) {
src.remove (count);
}
}
}
}
12 ListBox's full selection and non -full selection
If for the specified listbox, the following method can be passed into True or FALSE according to the needs of the user, which represents all the items in the full listbox or all the items. The code is 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] .select = isselect;
}
}
13 Move up and down the project in Listbox
The following code gives how to move the project in a listbox
Copy code code as follows:
Function listbox_move (listid, direction) {{
var listbox = document.GetelementByid (listid);
var selindex = listbox.selectEx;
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-) {{) {{
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.selectindindex = selindex + increment;
}
// ..
// ..
listbox_move ('Countrylist', 'Up'); // Move up the select option
listbox_move ('Countrylist', 'DOWN'); // Move down the select
14 Move the project in two different listboxes
If in two different listbox, you often need to move the project in a listbox on the left to another listbox. The following is the relevant code:
Copy code code as follows:
Function listbox_moveacross (sourceid, Destid) {
var src = document.getelementByid (sourceid);
var Dest = DOCUMENT.GetelementByid (Destid);
found that (var control = 0; count
if (src.options [count] .select == true) {
var option = src.options [count];
var newOption = document.createelement ("option");
newOption.value = Option.value;
newOption.text = OPTION.TEXT;
newOption.Select = 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', 'SelectDCountrylist');
15 Quick initialization of Javscript array
The following method gives a method of rapid initialization of the Javscript array. The code is as follows:
Copy code code as follows:
var number = [];
for (var I = 1; numbers.push (i ++) <100;);
// numbers = [0,1,2,3 ... 100]
Use the push method of the array
16 Test the decimal number of positioning
If you want to intercept the number of positions after decimal, you can use the TOFIXED method, such as:
Copy code code as follows:
var num = 2.443242342;
alert (num.tofixed (2));
The use of TopRecision (X) provides the precision of the designated bit. The x here is the entire number of digits, such as:
Copy code code as follows:
num = 500.2349;
result = num.toprecision (4); // Output 500.2
17 Check whether the string contains other strings
In the following code, you can check whether a string contains other string in a string. 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 rewritten in the above code and defined the contains method. The method of use is as follows:
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 repetitive elements in the Javscript array
The following code can remove the repetitive elements in the JavaScript array, as follows:
Copy code code as follows:
Function RemoveDuplicates (ARR) {
var test = {};
for (var I = 0; I <arr.Length; i ++)
temp [Arr [i]] = true;
var r = [];
for (var k in test)
R.PUSH (K);
Return r;
}
//usage
var fruits = ['apple', 'orange', 'peach', 'Apple', 'Strawberry', 'Orange'];
var uniqueFruits = RemoveDuplicates (from);
// Output uniquefruits ['Apple', 'Orange', 'Peach', 'Strawberry'];
19 Remove the excess space in String
The following code will add a trim () method to string. The code is 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"
20 redirection in JavaScript
In JavaScript, you can realize the redirection. The method is as follows:
Copy code code as follows:
window.location.href = "//www.vevb.com";
21 Code the URL
Sometimes, you need to encode the transfer in the URL. The method is 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/