JS Basics Review 6 (array, Json,getbyclass,select,math object)

Source: Internet
Author: User
Tags pow

first, an array of related operations 1. Definition(1) var arr=[1, ' abc ', function () {alert (3333);},[333,444]];   (2) var arr=new Array (12,5,8,9); If you put only one number, set the length (3) [] to a slightly higher performance because the code is short 2. Property ----Length (can be obtained and set)---Example: quickly empty an arrayvar a=[1,2,3,4,5,6,];     a.length=0; alert (a); (1) If the set length is more than the contents of the array, the actual content assigned to length (2) Only the array can manipulate length. (3) array can store any type of value (can be nested, add, overwrite, empty), but should try to save only one data 3. Adding a DELETE element (1) from the rear push (Element), add-----------Pop (element) from the tail, remove from tail (2) from the headunshift (), add------------Shift () from the head, remove from the headArr.push (4);     Arr.pop ();     Arr.shift (); Arr.unshift (0);
How to add an array two:
var arr=[];    arr[0]=33; arr[1]=44;arr[arr.length]=55;arr[arr.length]=66;arr[arr.length]=77; Add from behind
(3) Insert DeleteTo delete an element:Splice (beginning, length)---------------arr.splice (2,3)Insert element:Splice (start, length, inserted element 1, insert element 2, ...) ----can also be used as a replacement element                               If you insert only elements, you can set the length to 0 to insert the value in front of the first argument
var arr=[1,2,3,4,5,6];arr.splice (2,3); Arr.splice (2,0, ' A ', ' B ', ' C ', ' d '); alert (arr)
;
4. Sorting----sort ([comparison function]), string sorting var a=[' left ', ' right ', ' top ';    A.sort (); alert (a); Array Sorting can be used in this way:var a=[3,101,99,417];A.sort (function (n1,n2) {return n1-n2;        }); alert (a);
Example Three:Window.onload=function () {var arr=[-23,-452,0,4,6,123,734,1275,98,754];   for (Var i=0;i<arr.length;i++) {var min=arr[i];     Assume a minimum value of Var iminindex=i;                The lowest value corresponds to the subscript for (var j=i+1; j<arr.length;j++) {if (arr[j]<min) {min=arr[j];            Iminindex=j;        }        };        var c=arr[i];        Arr[i]=arr[iminindex];    Arr[iminindex]=c; } alert (arr);} Analog array Ordering: VAR arr=[2,45,78,12,46,1];
function Findinmin (Arr,start) {//Find the lowest value from the start position
Var imin=arr[start];//assumes that the first number of start is the minimum value;
Var iminindex=start;//assumes that the lowest value of the subscript is start;
for (Var i=start;i<arr.length;i++) {
if (Imin>arr[i]) {
Imin=arr[i];
Iminindex=i;
}
}
return iminindex;
}
for (Var i=0;i<arr.length;i++) {
var n=findinmin (arr,i); I value cannot be fixed;
var tem;
Tem=arr[n]; Min Arr[n] and arr[i] swap position
Arr[n]=arr[i];
Arr[i]=tem;
}
Alert (arr);
5. Conversion(1) concat(Array 2) Connect two arrays------------A.concat (b) var a=[1,2,3];    var b=[4,5,6]; Alert (A.concat (b)); (2) Join (delimiter)Combine array elements with separators, Generate Stringvar a=[1,2,3,4]; Alert (A.join ('-')); (3) reverse (): Anti- Turn Arrayvar str= ' What is your name '; var arr=str. Split(‘ ‘); ----- string to arrayArr.reverse ();--------------array inversion Str=arr.join (");-----------join and assign to String alert (str); array---> string: Join String---> array: Split two . JSON (object literal) 1. What is JSONis an object that stores data in a format var json{name 1: value 1, Name 2: Value 2, Name 3: Value 3, ...} {"Name": "Blue", "Age": "+", "Sex": "Male"} quotes are standard notation. If you interact with the background, you must use the standard notation alert (JSON.A); ==alert (json[' a '); Example: {"position": "Front engineer"," Age": "Up", {elder sister name: Little Red, elder sister position: Designer, elder sister age: 23},{two elder sister name: Floret, second sister position: Java engineer, second elder sister Age: *} 2.JSON standard notation var json={"a": "abc", "B": "Dddd"}When the last value ends, do not add a comma 3,json and Arrays                   subscript            length                 Cycle                                    Order
JSON strings are not allowed to be used in unordered order, in-time cannot be guaranteed to have an array number of values of any type With for/for in can be ordered ibid. 4. JSON and for inIn JS, generally, the name can be unquoted, and compatible for (Var i in JSON) {alert (i);   corresponding to each name alert (Json[i]); corresponds to each value} set style with JSON (i)Window.onload=function () {var obox=document.getelementbyid (' box ');                Obox.onclick=function () {SetStyle (obox,{width: ' 200px ', Height: ' 300px ',     Background: ' Red ', fontSize: ' 40px '//The last value ends without a comma});    }}function SetStyle (Obj,json) {for (var name in JSON) {Obj.style[name]=json[name]; }} Revision: Obox.onclick=function () {this.style.csstext= ' width:200px;height:300px;background:red;font-size:40px '// overwrites all of the original inline styles} set style with JSON (ii)Window.onload=function () {var Odiv=document.getelementbyid (' Div1 ');    var json={width: ' 400px ', Height: ' 400px ', background: ' Red '}; SetStyle (odiv, ' background ', ' red ');}    function SetStyle () {var obj=arguments[0];  if (arguments.length==3) {var name=arguments[1];  var value=arguments[2];    Obj.style[name]=value;  }else{var json=arguments[1];    for (var name in JSON) {Obj.style[name]=json[name]; }     }  } get the style, honestly with GetStyle third, Getelementsbyclassname get the element1. Document.getelementsbyclassname get elements by class, regardless of hierarchy. ie8--: Object not supported 2. function Encapsulationfunction Findinarr (N,arr) {
for (Var i=0;i<arr.length;i++) {
if (N==arr[i]) {
return true;
}
}
return false;
}
function Getbyclass (oparent,sclass) {
if (oparent.getelementsbyclassname);
{return oparent.getelementsbyclassname (sclass);}
else{
var aele=oparent.getelementsbytagname (' * ');
var arr=[];
for (Var i=0;i<aele.length;i++) {
var tem=aele[i].classname.split (');
if (Findinarr (Sclass,tem)) {
Arr.push (Aele[i]);
}
}
return arr;
}
}
Iv. Select ElementDirect Value property: Incompatible: No value Added 1, selectedindex---the subscript of the current option var ao=os1.options; Select all the option oS1 below;
var option=new option (' Hebei ', ' HB ');
Os1.add (option);//Add an option
Os1.remove (1);//delete the option labeled 1 os1.options. selectedindex;//the selected itemalert (os1.options[os1.selectedindex].innerhtml);//The contents of the currently selected option text 1;alert (os1.options[os1.selectedindex].text);//The contents of the currently selected option text 2; 2. Options: An array of all optionsEach of these options has two properties:(1) Value(2) Text 3, can be set length:oS1.options.length;4. A custom attribute that has never been defined-----undefined A variable that has never been defined------an error Five, onchange (compared to onfocus, onblur)Ose.onchange=function () {}--------------- when the drop-down menu changesExecution code is triggered only if it is used on a text box and needs to lose focus, and is rarely used for text boxes window.onload=function () {var ose=document.getelementbyid (' se ');    Ose.onchange=function () {alert (this.value); }} vi. Math Object 1, take the whole(1) Math.ceil ();----> Rounding Up (2) Math.floor (),----> Down rounding (2) math.round ();---> Rounding 2. Absolute value---->Math.Abs (); 3, open square----&GT;MATH.SQRT (); Power---->math.pow (A, b);----A 4. Maximum Value---->math.max (A,B,C),----maximum in >a, B, c Minimum Value---->math.min (A,B,C); Seven, batch set style 1. css Text------can set a variety of styles at once, but when you manipulate the inline style, other styles are overriddenODiv.style.cssText 2. with-----disorder, affecting performance 3, ClassName----recommended "Summary of this lesson" 1, when to add brackets, when do not add? (1) The function parentheses are executed immediately, onclick=undefined (2) Findinarr (); the function function is enclosed in parentheses to allow it to execute immediately. 2, why add a semicolon? The end of each sentence to add 3, arguments---get a parameter array 4. Closed Space---Avoid duplicate names, everything inside the function is local. 5. Get non-inline stylesCURRENTSTYLE[ATTR] getComputedStyle (obj,false) [attr] cannot read compound style, cannot set compound style 6. Batch set style(1) Csstext No, will cover other lines (2) with no, too messy and impact performance (3) JSON, can be used 7. Arrays(1) Define New Array (2) Length: Readable, assignable (3) method: Push pop shift unshift concat join Splice Reverse Sort 8. StringIndexOf lastIndexOf substring split touppercse tolowercase charAt 9. SelectValue SelectedIndex Options  10. Date0 Last day of last month35 extra days automatically counted in next month 11. MathCeil round floor abs sqrt POW Max min random

JS Basics Review 6 (array, Json,getbyclass,select,math object)

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.