JavaScript Knowledge point 1

Source: Internet
Author: User
Tags array definition array length bitwise bitwise operators logical operators



A JS variable



Name:


    • By English alphabet, numbers. An underscore consisting of an initial letter or an underscore or dollar sign $. Avoid using keywords and reserved words.
    • Variable names are case-sensitive.
    • Variable name two ways:


[1] Hump naming method: The first letter lowercase, the first letter of each word is capitalized; the words are separated by underscores; the first letter of each word is capitalized



[2] Hungarian nomenclature: Variable name = Type + Object description, such as Obtn,o for object type, btn for buttons, etc.



2--statement


    • VAR, let, const,
    • Variables that are not declared directly to be used directly become global variables and are not recommended.


The variable declared by Ps:var is advanced to the top of the function body. Functions are also declared in advance.



3--Variable Type


    • Value type: Take up space fixed, save in the stack, save and copy is the value itself; Use typeof to detect data type; Basic type data is a value type. Access by value allows you to manipulate the actual values that are saved in the variable. such as null, Undefined, number, String, Boolean.
    • Reference type: Occupy space is not fixed, save in the heap, save and copy is a pointer to the object, use instanceof to detect the type of data; The object constructed with the new () method is a reference type. Accessed by reference, the object's memory space cannot be manipulated directly. such as object.
    • Type conversions: Conversion functions (parseint (), parsefloat (), number ()), coercion of type conversions, use of JS weakly-typed conversions


Ps: If the defined variable is to be used to save the object in the future, it is better to initialize it to null so that you can check null directly to know if the corresponding variable has saved a reference to an object. As long as the variable intended to save the object has not actually saved the object. You can have it save a null value. The parameters of all functions are passed by value.



4--Scope


    • Global variables: Variables defined outside the body of the function or declared without VAR, defined within the body of the function; Global variables can be called at any location. A global variable is a property of a global object that persists unless it is shown to be deleted.
    • Local variables: Use variables such as Var declared inside the function or parameter variables of the function, and local variables must be called inside the body of the current function. A local variable is the property of the calling object, from the time it is declared to the end of the function's run or the end of its life cycle being displayed.
    • Precedence: Local variables are higher than global variables with the same name, parameter variables are higher than global variables with the same name, local variables are higher than parameter variables with the same name.


Ps: The inner layer function can access the outer function local variable, and the outer function cannot access the inner function local variable. Garbage collection mechanism: Mark Clear Method (main), reference counting method. To ensure that the memory is effectively reclaimed, the global variables that are no longer used should be released in a timely manner.






Two JS operators



The sum arithmetic operator:



+: (Concatenation of strings, two ways, the String + string, both directly splicing, or string + value, that is, the value of the string and then splicing; convert a numeric value to a string, that is, a value + an empty string;),



-: (Inverse operation of operands; subtraction of numbers; Convert string to numeric value, numeric string-0)



*: (Multiplication of two operands; the same number is positive, the number is negative)



/: (divide two operands; the same number is positive, the number is negative)



%: (returns the remainder of the two divisor; the symbol is the same as the first operand)



+ =:



-=:



*=:



/=:



%=:



+ +: (self-add operation)



--: (self-subtraction operation)



ps:++ 、--operation = "The operand must be a variable, an element of an array, or an object's property; If the operand is non-numeric, it needs to be converted to a numeric type; the operator is preceded by a self-addition/subtraction operation, then evaluated, and the operator is evaluated first, then the self-add/subtract operation is performed;






2--logical operators:



Logical Non! : null string, 0, NULL, NaN, undefined, return False if the return value is true, object, non-empty string, non-0 value, = = "Returns True if the value of the operand is false, otherwise returns false; two times continuous use!" , any type can be converted to a Boolean value;






Logic and &&: If the first operand is an object, the second operand is returned, the second operand is the object, the object is returned when the first action value is true, and if the two operands are objects, the second operand is returned, and an operand is null, and NULL is returned; If one of the operands is Nan, the Nan is returned; If an operand is undefined, return undefined; = = Returns true if and only if two operands are true; the second operand is not evaluated when the value of one operand is false;






Logical OR | | : The first operand is returned if the first operand is an object, the second operand is returned if the first operand is false, the first operand is returned if the two operands are objects, or null if the two operands are null, or if the two operands are Nan, a nan is returned; If two operands are undefined, return undefined; = = returns False if and only if the value of two operands is not false; If the first operand is true, the second operand is not evaluated;






3--Bitwise operators:



Type: Signed (the first 31 is a value bit, the 32nd bit is a sign bit, 0 is a positive number, 1 is a negative number), unsigned (only positive, 32nd digit, numeric range can be increased)



Value range: -231-231-1, i.e.-2147483648-2147483647



Storage mode: Positive number (pure 2 binary storage, each of the 31 bits represents a power of 2, with 0 complementary useless bits), a negative number (2 twos complement storage, and the complement calculation = = Determines the binary representation of the non-negative version of the digit, obtains the binary inverse code, i.e. 0 is replaced by 1, 1 is replaced by 0, and 1 is added to the binary counter code)



The special values treated as Infinity are Nan,






Logical bitwise OPERATIONS: The return value of 1 has a = = bitwise NON ~ 0, the bitwise AND & corresponding bits are all 1, bitwise OR |  Any one is 1, the bitwise XOR or ^ is neither 0 nor 1; The return value of 0 has a = = bitwise NON ~ 1, bitwise and & any one is 0, bitwise, or | Corresponding bits are all 0, bitwise XOR or ^ corresponding bits full 0 or all 1






Shift Action: Shift left (all bits of the value are shifted to the left of the specified number of digits, all vacancies with 0 complement, left 1 bits to it by 2, left two bit by 4 ...) ), signed right shift (moves all bits of a numeric value to the right of the specified number of digits, the moved out bit is discarded, retains the sign bit, moves right 1 bits to it except 2, shifts 2 bits to the right except 4 ...). ), unsigned Right shift (positive, same as signed right shift, negative, infinite value ...) )






PS: If a bitwise operation is performed on a non-numeric value, it is converted to a numeric value (auto-complete) using the number () function before the bitwise operation. The essence of bitwise negation is its negative number minus 1.






4--Relational operators:


    • Size Relationship Detection:


< returns True if A<b, otherwise false



<= if a<=b, returns True, otherwise false



>= if a>=b, returns True, otherwise false



> Returns True if A>b, otherwise false






The numerical and numerical comparisons are compared to their algebraic values;


    • Only one operator is a numeric value, the other operand is converted to a numeric value, and its algebraic values are compared;
    • Comparisons between strings, each of which compares their Unicode values by character;
    • A comparison between a string and a non-numeric value, converting the operand to a string and comparing it;
    • The operand is neither a number nor a string, and is converted to a numeric or string comparison;
    • The operand cannot be converted to a numeric value or string and returns false;
    • Compared to Nan, the return value is false;





Equivalence relationship detection:


    • Equality comparison:


= =: is the return value equal to the two operands



! =: Compare whether the return value of two operands is not equal



Ps: Object-Call ValueOf (), string-to-numeric comparison, string conversion to numeric value, NULL is equal to undefined, no conversion is made before comparison, Nan is not equal to any value, including itself, whether the object belongs to the same object, is = =, no! =


    • Same comparison:


= = =: Compares the return value and data type of two operands;



!==: Compare the return value and data type of two operands;



Ps: Comparison between value types, only the same data types and values equal; Value types are certainly not the same as reference types; Comparisons between reference types compare their reference values (memory addresses)






5--Object operators:


    • In: Determines whether the left-hand operand is a member of the right operand
    • instanceof: Determining whether an object instance belongs to a class or constructor
    • NEW: Creates an object based on the constructor and initializes the object
    • Delete: Deletes a property, array element, or variable of the specified object
    • . and []: accessing objects and array elements
    • (): function call, change operator precedence, etc.








6--Conditional operators:



Boolean_expression? True_value:false_value






7--Assignment operators:



=






8--comma operator:



Perform several different actions within a row






9--typeof operator: type-judging operator






10--void: Discards the value of the operand and returns the value of undefined as the expression









Three JS process (control) statement





    • Conditional selection Structure: If, if-else, if-else-if, switch
    • Loop structure: For, for-in, while, do-while
    • Other statements: Break, continue, return, with, label
    • Exception Handling Statements: Throw (unsolicited exception), try (indicates code snippet to be processed), catch (catch Exception), finally (post-processing)





Four JS arrays






How to create a method:



Empty array: var obj=new array (), or Var obj=[];



Specify an array of lengths: Var obj=new array (length), or Var obj=array (20)



Specify an array of elements: Var obj=new array (ele1,ele2,..., EleN), or Var obj=[1,2,3];



Single-dimension array: var obj=[ele1,ele2,..., EleN], or var obj=new array ("Red", "blue")



Multidimensional array: var a=new array ([ARR1],[ARR2],..., [ARR3]);






2--Basic Operation:



Access array elements: (1) Single-dimension array: array name [subscript index]; (2) Multidimensional array: array name [outer array subscript] PS: Array length is variable, array subscript starts at 0, subscript type has numeric and non-numeric type, there are several cases of non-numeric type: to string or generate associative array or subscript will be the name of the object property, array elements can be added to the object. such as read Arr[2] or set arr[2]= "Blue"



Add array: Use the [] operator to specify a new subscript, such as 3,arr[3]= "Loj"



Delete array: delete array name [subscript]



Iterating through an array: for (var array element variable in array)



Detection array: Array.isarray (value)



eg.


var vals=[1,2,3]; 
console.log(vals[2]); 
vals[vals.length]="black"; 
vals[vals.length]="red"; 
console.log(vals);
if(Array.isArray(vals)){ 
    console.log("we get"); 
  }

 





Array properties: Constructor: (constructor referencing array object), Length: (Returns the length of the array), prototype (extended array definition by adding properties and methods)



The Ps:length property is not read-only, the array element can be deleted and added by length, if the array length is set less than the actual array element, the corresponding array element will be removed from the end of the array, if the array length is greater than the number of actual array elements, A new array element is added to the array with a value of undefined






3--Array Method:



To add an element:



Push (): (adds an array at the end of the array and returns the length of the modified array),


var colors = new Array ();
var count = colors.push ("red", "blue"); // Push () operation returns the length of the array, that is, assign the length of the array to the variable count
console.log (count); // 2





Unshift (): (adds any number of elements to the head of the array and returns the length of the new array),


var colors=new Array(); 
var count=colors.unshift("red","bleu"); 
console.log(count);//2 
count=colors.unshift("black"); 
console.log(count);//3 
var item=colors.pop(); 
console.log(item);//bleu 
console.log(colors.length);//2





Concat (): (merges two or more arrays and returns a new merged array)



Creates a copy of the current array, adds the received parameters to the end of the copy, and finally returns the newly constructed array. When you pass a parameter to concat (), just copy the current array and return its copy. If the parameter passed to it is one or more arrays, the method adds each item in the array to the result array. If the pass is not an array, the values are added directly to the end of the array.


var colors=["red","blue","green"]; 
var colors2=colors.concat("yellow",["black","pink"]); 
console.log(colors2);//[ ‘red‘, ‘blue‘, ‘green‘, ‘yellow‘, ‘black‘, ‘pink‘ ] 
console.log(colors);//[ ‘red‘, ‘blue‘, ‘green‘ ]





To delete an element:



Pop (): (Delete and return the last element of the array),


var colors = new Array ();
var count = colors.push ("red", "blue"); // Push () operation returns the length of the array, that is, assign the length of the array to the variable count
console.log (count); // 2
var item = colors.pop (); // pop () operation deletes the last element of the array and returns, the last element to be deleted is assigned to the variable item
console.log (item); // blue





Shift (): (Deletes and returns the first element of the array, minus 1 of the array length)


var colors=new Array(); 
var count=colors.push("red","bleu"); 
console.log(count);//2 
count=colors.push("blaj"); 
console.log(count);//3 
var item=colors.shift(); 
console.log(item);//red 
console.log(colors.length);//2





Sub-arrays:



Splice (): (delete any number of items = = Splice (The starting subscript to be deleted, the number of items to be deleted), insert the specified item at the specified position = splice (starting subscript, 0, the item to be inserted); Replace any number of items = Splice (starting subscript, The number of items to be deleted, the item to insert))



The Ps:splice () method always returns an array that contains the items removed from the original array, and an empty array if no items are deleted. and splice () will change the original array.


var colors=["red","blue","green","yellow"]; 
var removed=colors.splice(0,1); 
console.log(colors);//[ ‘blue‘, ‘green‘, ‘yellow‘ ] 
console.log(removed);//[ ‘red‘ ] 
 
removed=colors.splice(1,0,"yellow","orange"); 
console.log(colors);//   [ ‘blue‘, ‘yellow‘, ‘orange‘, ‘green‘, ‘yellow‘ ] 
console.log(removed);//  [] 
 
removed=colors.splice(1,1,"red","purple"); 
console.log(colors);// [ ‘blue‘, ‘red‘, ‘purple‘, ‘orange‘, ‘green‘, ‘yellow‘ ] 
console.log(removed);//  [ ‘yellow‘ ]





Slice (): (selects some elements from an existing array to form a new array; Slice (returns the starting position of the item, returns the end position of the item); PS: If a negative number, then use the array length plus the value to determine the position, the starting position is the actual subscript of the value; If only one parameter is passed in, it is returned from the specified position of the parameter to the end of the array; the slice () method does not affect the original array)


var colors=["red","blue","green","yellow"]; 
var colors2=colors.slice(1); 
var colors3=colors.slice(1,4); 
console.log(colors);//[ ‘red‘, ‘blue‘, ‘green‘, ‘yellow‘ ] 
console.log(colors2);//[ ‘blue‘, ‘green‘, ‘yellow‘ ] 
console.log(colors3);//[ ‘blue‘, ‘green‘, ‘yellow‘ ]





4--Array Sorting:



Reverse (): (Reverses the order of the elements in the array)



Sort (): (sort a character array or array of numbers, default by string comparison, or write sort function support yourself)



The Ps:sort () method arranges array items in ascending order, and sort () calls the ToString () transformation method to compare the resulting string to determine how to sort. The sort () method can also receive a comparison function as a parameter, which allows us to specify which value precedes it. The comparison function receives two parameters, returns a negative number if the first argument should precede the second argument, returns 0 if the two arguments are equal, or returns a positive number if the first argument should be after the second argument.


return 0;
         }
         }
         function compare1 (a, b) {// Suitable for numeric type or its valueOf () will return numeric type object type
              return a-b;
        }
         var values = [1,3,10,35,8];
         var vals = [1,5,6,10,8]
         values.sort (compare1);
         vals.sort (compare);
         console.log (values); // [1, 3, 8, 10, 35]
         console.log (vals); // [1, 5, 6, 8, 10]





PS: Because the comparison function affects the sorting result by returning a value that is less than 0, equal to 0, or greater than 0, the subtraction operation can handle all of these cases appropriately.






Array conversions:



ToString (): (converted to string and returned)



toLocaleString (): (converted to local format string and returned)



ValueOf (): (returns a comma-delimited string of strings for each value in the array)



Join (delimiter): (splits an array with the specified delimiter and converts to a string)






eg.


var arr=[1,2,6,8,9]; 
console.log(arr.toString());//1,2,6,8,9 
console.log(arr.valueOf());// [ 1, 2, 6, 8, 9 ] 
console.log(arr);//  [ 1, 2, 6, 8, 9 ]





Ps:tostring (), tolocalestring (), ValueOf (), by default, return array items as a comma-delimited string, and join () can use a different delimiter to construct the string.









5--Location Method:



IndexOf (ARG1,ARG2): (Looks backwards from the beginning of the array, returns the position of the item to find in the array, or-1)



LastIndexOf (ARG1,ARG2): (looks forward from the end of the array, returns the position of the item to find in the array, or-1)



PS: Parameters: The item to find, the location index that represents the start of the lookup (optional parameter). Use congruent operators when comparing.


var nums = [1,2,3,4,5,4,3,2,1];
console.log (nums.indexOf (4)); // 3
console.log (nums.lastIndexOf (4)); // 5, the index is defined from the front to the back
console.log (nums.indexOf (4,4)); // 5
console.log (nums.lastIndexOf (4,4)); // 3
 
var person = {name: "Nicho"};
var people = [{name: "Nicho"}];
var morePeople = [person];
console.log (people.indexOf (person)); //-1
console.log (morePeople.indexOf (person)); // 0





6--Iteration method: (Same point: Run a given function for each item in an array)



Every (): (returns True if the function returns true for each item)



Filter (): (All members that return a value of true)



ForEach (): (No return value)



Map (): (returns an array of results for each function call)



Some (): (returns True if any of the items returns True)



PS: Receive parameters: The function to run on each item, the scope object that runs the function, the passed-in parameter of the Run function: The value of the array item item, the position of the item in the array index, the array object itself array






Every (), some () is used to query whether an item in the array satisfies a condition, and for every (), the passed argument must return true for each entry, and the Some () method returns True if the passed function returns true for an item in the group.


var nums=[1,2,3,4,5,4,3,2,1]; 
var everyResult=nums.every(function(item,index,array){ 
    return (item > 2); 
}); 
console.log(everyResult);//false 
 
var someResult=nums.some(function(item,index,aray){ 
    return (item > 2); 
}); 
console.log(someResult);//true








Filter (): uses the specified function to determine whether an item is included in the returned array, such as returning an array where all the values are greater than 2. This method is useful for querying all array items that meet certain criteria.


var nums=[1,2,3,4,5,4,3,2,1]; 
var everyResult=nums.every(function(item,index,array){ 
    return (item > 2); 
}); 
console.log(everyResult);//false 
 
var someResult=nums.some(function(item,index,aray){ 
    return (item > 2); 
}); 
console.log(someResult);//true





Map (): Returns an array with each item running the result of an incoming function on the corresponding item in the original array, such as multiplying each item in the array by 2, and then returning an array of these products


var nums=[1,2,3,4,5,4,3,2,1]; 
var everyResult=nums.every(function(item,index,array){ 
    return (item > 2); 
}); 
console.log(everyResult);//false 
 
var someResult=nums.some(function(item,index,aray){ 
    return (item > 2); 
}); 
console.log(someResult);//true





ForEach (): Just run the incoming function for each item in the array, no return value.






7--Merge Method:



Reduce (): (traversing from the beginning of the array)



Reduceright (): (traversing from the end of the array)



PS: Receive parameters: The function that is called on each item, the initial value that is the base of the merge; incoming parameter: Current value prev, current value cur, index of item, array object



PS: Both methods iterate through all of the items in an algebraic group and then build a value that is ultimately returned. Any value returned by the passed-in function is automatically passed to the next item as the first argument, that is, the first iteration occurs on the second item of the array, because the first parameter is the first item in the array, and the second is the second item of the array.


var nums=[1,2,3,4,5]; 
var sum=nums.reduce(function(prev,cur,index,array){ 
    return prev + cur; 
}); 
console.log(sum);//15

 
var nums=[1,2,3,4,5]; 
var sum=nums.reduceRight(function(prev,cur,index,array){ 
    return prev + cur; 
}); 
console.log(sum);//15








PS: Reference: JavaScript Advanced Program design, JavaScript authoritative guide, the Atlas of a Netizen (address forgot)



Not to be continued ...



JavaScript Knowledge point 1


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.