Introduction to JavaScript from Beginning to Proficiency: Functions and Arrays

Part II Functions and Arrays

1. Functions

Definition of function

Ordinary function

  • Function function name (expression 1...) {Code Block}
  • js is an interpretative language. At the beginning of script tag code execution, ordinary functions are put into the heap, and only references are put into the heap. The contents of functions are not interpreted and executed. Only when functions are executed, can they be parsed, executed once, and parsed once.
  • Ordinary function fn() {} can be called to execute before it is defined
fn(); // You can call it before defining it
function fn() {
	console.log('Ordinary function');
}
fn(); // It can also be called after definition
  • Danger of function renaming
    1. Common function and anonymous function are renamed, and anonymous function overrides ordinary function. The reason is that ordinary function puts function into heap at the beginning of script tag, while anonymous function is stored in heap at the time of code parsing. If the name is the same, the original function will be overwritten.
    2. Common function and variable rename, variable will cover common function;
      Example:
//  1. Rename of normal and anonymous functions
function fn() {
	console.log('I am a normal function.');
}
var fn = function() {
	console.log('I am an anonymous function');
}
fn(); // Output: I am an anonymous function
//  2. Rename of Common Functions and Variables
function fn() {
	console.log('I am a normal function.');
}
var fn = 10;
fn(); // Failure of the call will result in an undefined error in fn

Anonymous function

  • Definition: var variable = function() {code block}
  • Assigning an anonymous function to a variable is what executes the variable function. An anonymous function can no longer be called before defining the function.
var fn = function() {
	console.log('Anonymous function');
}
fn(); // Anonymous functions can only be called after definition
  • Anonymous functions are not recommended, and addEventListener() is usually used instead.
// Excellent compatibility ie6 +, but not recommended
btn.onclick = function() {
	console.log(this); 
}
// Usually replaced by the following way, compatibility ie8+
btn.addEventListener('click', clickHandler);
function clickHandler(e) {
	console.log(e);
}

Constructor

  • Definition: var variable = new Function (parameter string, execution statement code block string)
  • Using a full string, the parameters are at the front, followed by a statement that executes the code.
  • Disadvantage: Code can be executed twice, the first time the string in the function will be parsed into ordinary code, and the second time the code will be executed, so the efficiency is very low.
  • Advantages: You can import the js code in any language and execute it
var fn = new Function("a", "console.log(a)");
fn(10); // Output 10

Self-executing function

  • Definition: (function () {code block} ()
  • The self-executing function can only be executed once, and it can't be found after execution. It becomes an orphan object (but it can't be reclaimed with references).
(function () {
	console.log('Self-executing function');
})();

Scope of variables

global variable

  • The so-called global variable is a variable defined directly by var in script tags.
  • When a variable is defined in script, the call is undefined before definition. This is because the defined variable opens up the storage location of the variable in memory, and when the code is interpreted and executed, the value will be stored in the stack. If called in advance, the computer will not find the corresponding storage location in memory, so undefined will be reported.
console.log(s); // Error reporting: s is not defined 
var s = 100;
  • If the variable defined in the next script is called in the previous script, it will always report an error because no storage space is opened.
<script type="text/javascript">
  console.log(s); // Error reporting: s is not defined 
</script>
<script type="text/javascript">
  var s = 100;
</script>
  • Once the variables are defined, they can be called arbitrarily in subsequent script s because they are global variables.
<script type="text/javascript">
  var s = 100;
  console.log(s); // Output: 100
</script>
<script type="text/javascript">
  console.log(s); // Output: 100
</script>

local variable

  • A local variable is a variable defined by var in a function.
  • Local variables defined in a function are scoped, and their scope is limited to the inside of the function. When the function is run, the variables defined in the function will be destroyed automatically.
var s;
function fn() {
	var c = 10; // This is a local variable.
	c += 3; 
	console.log(c); // Output: 13
	// The value of the global variable can be modified in the function. After modification, the global call is valid.
	s == 10;
	console.log(s) // Output: 10
}
fn();

Rename of local and global variables

  • If a local variable name is defined in a function, then all the variables in the function are local variables and cannot be invoked to the global variable with the same external name by directly using the variable name.

Example:

 var s = 10;
 function fn() {
 	var s = 20;
 	s += 20;
 	window.s += 10; // To call a global variable with the same name as a local variable in a function, you need to add a window prefix
 	console.log(s); // Output: 40
 	console.log(window.s); // Output: 20
 }
 fn();

Typical examples

 var s = 10;
 function fn() {
 	console.log(s); // Output: undefined
 	s += 20;
 	console.log(s); // Output: NaN because it is undefined += 10
 	var s = 20;	// Once defined within a function, calls before and after it are layout variables
 }
 fn();

parameter

Definition

Since js is a weakly typed language, the following two points should be noted when using parameters

  • Parameter type: Because the parameter type cannot be fixed, if it is an open function parameter, it must be judged in the code the type of input parameter.
  • Initialization: In ES5, the parameters of the function can not set the initialization value, so you need to customize a default initial value when executing the code; in ES6, there are initialization parameter settings that can be used directly, such as function(a, b, type='+'), parameter type is "+" by default.

References and Formal References

Object parameters

If the parameter is an object, the address of the reference object is passed in

function fn(o) {
  var obj = {a: 1};
  console.log(o === obj); // false
  console.log(o === obj3); // true
}
var obj3 = {a: 3};
fn(obj3);

Function parameter - callback

If a parameter is passed in a function name and runs this parameter in the current function, it is called a callback.

function fn1(o, fn){
	o.a += 1;
	fn(o); // CCCallFuncN
	console.log(o.a); // Output: 12
}
function fn2(_o){
	_o.a += 10;
}
var obj = {a: 1};
fn1(obj, fn2);

Functions Execute themselves - Recursion

var sum1 = 0;
var i = 0;
function fn() {
  if (i === 100){
  	return// Jump out of function
  }
  sum += i;
  i++;
  fn(); // CCCallFuncN
}

return

Matters needing attention

  • The return statement terminates the execution of the function and returns the value of the function. Return is the keyword for the return value of the function in JavaScript.
  • The results processed within a function can be returned using return, so that the returned results can be accepted with variables where the function is called.
  • Any type of variable data or expression in the return keyword can be returned, or even nothing can be returned.
  • return can also be used as a statement to prevent subsequent code execution
  • Function ABC () {if (bool) return} can effectively control the execution of statements under certain conditions, but it must be distinguished from break. Break is used in conditions and only jumps out of conditions and loops, but return can jump out of functions, only for functions, and RET can not be used without functions. Urn

Application scenarios

  1. Return a data
function createObj(_a) {
	return {a: _a}; // Returns a data object
}
console.log(createObj(3) === createObj(3)); // Output: false
  1. Factory mode or singleton mode
var box;
function createBox(_a, _b) {
	if (!box) {
		box = {};
	}
	box.a = _a;
	box.b = _b;
	return box;
}
console.log(createBox(3, 5) === createBox(10, 20)); // Output:true
  1. Objects passed in through parameters
function setObjProper(obj) {
	obj = obj || {}; // Wide mode
	obj.n = 3;
	return obj;
}
var obj = setObjProper({});
var obj1 = setObjProper();
var obj2 = {a: 5};
console.log(obj2 === setObjProper(obj2)); // Output:true
console.log(obj, obj1); // Output: {n: 3} {n: 3}
  1. If the parameter is a function, the result of the callback function is returned.
function fn1(fn) {
	var obj = {};
	return fn(obj); // Returns the result of the callback function
}
function fn2(obj) {
	obj.a = 10;
	return obj;
}
console.log(fn1(fn2)); // Output: {a: 10}
  1. Returns a private object (closure)
function fn() {
	return function () {
		console.log('aaa');
	}
}
fn()(); // Output: aaa
  1. Returns an array and multiple elements
  2. Returns an object and multiple elements
  3. Returns a function body
  4. Jump out

2. Arrays

Definition

  • The data is arranged in an orderly manner and stored in a variable.
  • There is no array type in native JS, and data in native JS can store multiple different types of data (weak type)
  • Array.isArray(arr) is to determine whether an arr is an array or not.
  • In an array, the location of the identifying element is called subscript, or index.
  • In an array, the content of the identifying element, arr[0], is called the subscript variable.

Array creation

  1. Literal Quantity Creation
    var arr = [1, 2, 3, 4, 5]
  2. Object constructor creation
    var arr = new Object([1, 2, 3, 4, 5])
  3. Constructor creation
    var arr = new Array()
    Be careful:
    • When an array is created, there is only one parameter of numerical type, which is the length of the array.
    • When you create an array, you have and only have a parameter of non-array type or two or more parameters, all of which are elements of the array.

The length of the array

  • Array length can be set
  • Set the length of the array to 0 to represent the empty array
  • If the array length is less than the original array length, it means that the array is truncated from 0 bits to the specified position.
var arr = [1, 2, 3, 4, 5];
arr[arr.length-1] = 6; // Replace the last element 5 in the array with 6
arr[arr.length] = 6; // Add a new element 6 to the end of the array

Traversal of arrays

  1. for loop traversal
var arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
	console.log(i + '=====' + arr[i]); 
	// Output: 0=======1
    //		 1=====2
    //       2=====3 
    //       3=====4 
    //       4=====5
}
  1. for in traversal (traversal of all objects in an array)
var arr = [1, 2, 3, 4, 5];
arr.key = 100;
for (let prop in arr) {
	console.log(prop + '=====' + arr[prop]); 
	// Output: 0=======1
    //		 1=====2
    //       2=====3 
    //       3=====4 
    //       4=====5
    //       key=====100
}
  1. forEach traversal
    forEach traverses the current array, does not return a value, and does not return a new array
var arr = [1, 2, 3, 4, 5];
arr.forEach(function(t, i, arr)) {// Parameters are: element values, element subscripts, array objects
	console.log(t, i, arr)
})
  1. map traversal
    map traverses the array and returns the elements in the current array to the new array. When returns are not applicable, the length of the new array is the same as that of the original array, but each element is undefined.
var arr = [1, 2, 3, 4, 5];
arr = arr.map(function (t) {
	if (t % 2 === 0) { // Even elements in array elements + 1
		return t + 1;
	}
	return t;
});
console.log(arr); // Output: [1, 3, 3, 5, 5]

Bubble sort

var arr = [6, 3, 4, 5, 7, 1, 2, 9, 0, 8];
// Point 1: Outer circulation from back to front
for (var i = arr.length; i > 0; i--) {
	// Point 2: Inner loop from front to back
	for (var j = 0; j < arr.length; j++) {
		// Point 3: Judge only the current and next size of the inner loop, and then swap
		if (arr[j] > arr[j+1]) { // Ascending order: J > j + 1 descending order: J < j + 1
			var temp = arr[j];
			arr[j] = arr[j+1];
			arr[j+1] = temp;
		}	
	}
}
console.log(arr); // Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Selective Sorting

var arr = [6, 3, 4, 5, 7, 1, 2, 9, 0, 8];
// Point 1: Outer loop from beginning to end
for (var i = 0; i < arr.length; i++) {
	// Point 2: Each initial minimum is the value of the current loop
	var min = i; 
	// Point 3: From the next item of the current value to the tail loop
	for (var j = min + 1; j < arr.length; j++) {
		// Point 4: Compare the sizes and find the subscripts of the lowest values in the following elements
		if (arr[min] > arr[j]) { // Ascending order: min > J descending order: min < J
			min = j;
		}
	}
	// Point 5: Exchange current and minimum subscriptions
	var temp = arr[i];
	arr[i] = arr[min];
	arr[min] = temp;
}
console.log(arr) // Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array Method

push

var arr = [1, 2, 3, 4, 5];
// Adding elements to the end of an array
var len = arr.push(6); // Returns the new length of the array
// Typical applications
var len = arr.push(6, 7, 8);
var len2 = arr.push([6, 7, 8]);
console.log(len, len2) // Output: 8 9

pop

// Delete the element at the end of the array
var t = arr.pop(); //Returns deleted elements
// Typical applications
var arr = [-2, -1, 0, 1, 2, 3, 4];
var arr1 = [];
var t;
while (t = arr.pop()) { // All elements after zero in arr are retrieved and arranged in reverse order
	arr1.push(t);
}
console.log(arr1); // [4, 3, 2, 1]

shift

// Delete the header element of the array
var t = arr.shift(); // Returns deleted elements

unshift

var arr = [1, 2, 3, 4, 5];
// Adding elements to the array header
var len = arr.unshift(); // Returns the new length of the array
var len = arr.unshift(0); // [0, 1, 2, 3, 4, 5]
// Minimize the use of unshift and add element cost performance from the array header

join

var arr = [1, 2, 3, 4];
console.log(arr.join()); // Same as arr.toString()
console.log(arr.join('#')); // Set a symbol to link each element of the array to form a new string.
console.log(arr.join('')); // Elements are closely linked 

concat

var arr = [1, 2, 3, 4];
var arr1 = arr.concat(); // No number of parameters, representing a replicated array
var arr2 = arr.concat(5, 6); // Link arr arrays to 5,6 elements to form new arrays with the original array unchanged
var arr3 = arr.concat([5, 6, 7]); // Combine arrays and arrays [5, 6, 7] to form new arrays
var arr4 = [5, 6, 7];
var arr5 = arr.concat(arr4); // Link two arrays to form a new array

splice

var arr = [1, 2, 3, 4, 5];
arr.splice(); // Array inserts delete replacement elements and returns deleted elements to be combined into a new array
var arr1 = arr.splice(); // Create a new empty array to return
var arr1 = arr.splice(3); // Delete from subscript 3 to tail
var arr1 = arr.splice(0); // Import all elements of arr into arr1 and clear arr
var arr1 = arr.splice(0, 2); // Delete 2-bit elements from subscript 0 of arr array
var arr1 = arr.splice(0, 0, -1); // Insert a - 1 at bit 0
var arr1 = arr.splice(-1, 0, -1); // Insert A-1 in BIT-1 (penultimate 1)
var arr1 = arr.splice(arr.length, 0, -1); // Insert a - 1 at the end of the array
var arr1 = arr.splice(1, 2, -1, -2); // Replace two elements with - 1, - 2 from the first place

slice

var arr = [1, 2, 3, 4, 5];
arr.slice(); // Array intercepts elements and returns the intercepted elements to be combined into a new array with the original array unchanged
var arr1 = arr.slice(); // Copy all elements of arr to arr1, without reference to the original array
var arr1 = arr.slice(0); // Copy all elements of arr to arr1, without reference to the original array
var arr1 = arr.slice(3); // Truncate arrays from subscript 3 to the end to form new arrays
var arr1 = arr.slice(-2); // Truncate arrays from the penultimate to the end to form new arrays
var arr1 = arr.slice(3, 4); // Intercept arrays from subscript 3 to subscript 4 to form new arrays
var arr1 = arr.slice(-2, 4); // Cut the array from the penultimate to subscript 4 to form a new array
var arr1 = arr.slice(-2, -1); //  Intercept the array from the penultimate to the penultimate to form a new array

indexOf

var arr = [1, 2, 3, 4, 5];
arr.indexOf(); // Find the element in the array, return the subscript of the element found, and do not find the return - 1
console.log(arr.indexOf(2)); // Look back for 2 from 0
console.log(arr.indexOf(2, 3)); // Look back for 2 from subscript 3

lastIndexOf

var arr = [1, 2, 3, 4, 5];
arr.lastIndexOf(); // Look back and forth in the array for the element, return the subscript of the element found, and find no return-1.
console.log(arr.lastIndexOf(2)); // Look back and forward for 2
console.log(arr.lastIndexOf(2, 3)); // Look forward 2 from subscript 3

reverse

var arr = [1, 2, 6, 4, 3, 5];
// Change the original array in reverse order, returning a new array and an original array as a reference relationship
var arr1 = arr.reverse();
console.log(arr, arr === arr1); // Output: [5, 3, 4, 6, 2, 1] true

sort

var arr = [1, 12, 6, 4, 3, 5];
// Sort the elements in the original array bit by bit, the original array changes, and the new array and the original array returned are reference relations.
var arr1 = arr.sort();
console.log(arr, arr === arr1); // Output: [1, 12, 3, 4, 5, 6] true
// sort(function(pre, next) {}); can achieve ascending and descending ordering
// Ascending Sort Output: [1, 3, 4, 5, 6, 12]
arr.sort(function(pre, next) {
	return pre - next; 
});
// Descending Sort Output: [12, 6, 5, 4, 3, 1]
arr.sort(function(pre, next) {
	return next-pre;
});

some

To determine whether all elements in an array satisfy a condition, if only one condition returns true, otherwise false is returned.

var arr = [1, 3, 5, 2, 7, 8, 0, 6]
var boolean = arr.some(function(t) {
	t ++;
	return t > 5;
})
console.log(boolean); // Output:true

every

Determine whether all elements in an array satisfy a certain condition, and return false only if all elements satisfy the return true

var arr = [1, 3, 5, 2, 7, 8, 0, 6]
var boolean = arr.every(function(t) {
	t ++;
	return t > 5;
})
console.log(boolean); // Output: false

filter

Determine whether all elements in an array satisfy a certain condition, and return a new array of all elements that satisfy the condition. The original array elements remain unchanged.

var arr = [1, 3, 5, 2, 7, 8, 0, 6]
var arr1 = arr.filter(function(t) {
	t ++;
	return t > 5;
})
console.log(arr1); // Output: [5, 7, 8, 6]

reduce

// If there is no initValue value, sum is the value of item 0, item is the first value, so index starts at 1.
var s = arr.reduce(function(sum, item, index)) {
	console.log(sum, item, index);
	return sum + item;
}, initValue); // The second parameter here is the initial value. If this initial value is set, index starts at 0.

from

var div = document.getElementsByTagName('div');
// es5: Converting objects into arrays
var arr = Array.prototype.slice.call(div); 
// es6: Converting objects into arrays
var arr = Array.from(div);

Array of parameters

  • In a function, if a parameter is written at the top of all the parameters, it is the necessary parameter.
  • All parameters in es5 generally need to be filled in in place. If they are not filled in, they will become undefined.
  • Multi-entry parameter values will not be obtained directly
  • If the parameters of a function are uncertain, we usually do not write parameters when defining the function, and use the parameter array arguments to process the function body.

Typical cases of arguments

// 1. Finding the Maximum of Several Numbers
function max() {
	var arr = Array.from(arguments);
	return arr.reduce(function(p1, p2){
		return p1 > p2 ? p1 : p2;
	});
}
console.log(max(1, 2, 3, 6, 3, 2, 6, 8, 9)); // Output: 9

// 2. Function callback
function fn() {
	console.log(arguments.callee); // Gets the currently executed function
	console.log(arguments.callee.a); // Get attribute values
	console.log(arguments.callee.caller); // Callback to the parent function of the current function
}
fn.a = 10; // Adding attributes to objects
fn(2, 3, 4); // Execution function
function fn2(fn) {
	fn();
}
fn2(fn); // Executing parent functions

Two-dimensional array

var arr = [
	[1, 2, 3, 4, 5],
	[1, 2, 3, 4, 5],
	[1, 2, 3, 4, 5],
	[1, 2, 3, 4, 5],
	[1, 2, 3, 4, 5],
]

Object data

var arr = [
	{a: 1, b: 2, c: 3},
	{a: 1, b: 2, c: 3},
	{a: 1, b: 2, c: 3},
]

Keywords: Javascript less Attribute

Added by truman on Sat, 07 Sep 2019 13:44:14 +0300