JavaScript Basics – built in objects (array objects)

Time:2022-5-13

Built in object

Array object

MDN document link:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

Object creation array

// 1.  Array letter quantity
var array = []; //  Create an empty array
var numbers = [1, 2, 4]; //

// 2.  Array constructor
var array = new Array(); //  Create an empty array
var numbers = new Array(2, 2, 5, 8, 9)

Judge array objects

  • instanceofOperator is used to detect whether the prototype attribute of the constructor appears on the prototype chain of an instance object.
  • console.error()Output an error message to the web console.
  • Array.isArray()Used to determine whether the value passed is an array.
//The first method is array instanceof array
function fn(arr) {
	if(!(arr instanceof Array)){
		console. Error ("the parameter arr is not an array object");
		return;
	}
	console. Log ("normal execution")
}
var numbers = [2, 5, 4];
fn(numbers);

//The second method is array Isarray() has a browser compatibility problem. Browsers that support HTML5 support this method
function fn(arr) {
	if (!Array.isArray(arr)) {
		console. Error ("the parameter arr is not an array object");
		return;
	}
	console. Log ("normal execution")
}
var d = 1;
fn(d);

ToString () and valueof () methods of array objects

Each object hastoString()andvalueOf()Two methods

var arr = [2, 5, 3, 5, 4];
// 1.  Tostring(), convert the array into a string, and separate each item with a comma
console.log(arr.toString()); // 2,5,3,5,4

// 2.  Valueof(), return the array itself
console.log(arr.valueOf()); // [2, 5, 3, 5, 4]

Common methods of array objects

// 1.  Stack operation, first in and last out
//Push() adds one or more elements to the end of the array and returns the new length of the array (this method modifies the original array).
//Pop(), deletes the last element from the array and returns the value of the element. This method changes the length of the array.
var arr = [1, 2, 3, 4, 5, 6];
arr.push(7);
console.log(arr); // [1, 2, 3, 4, 5, 6, 7]
var arrPop = arr.pop();
console.log(arr); // [1, 2, 3, 4, 5, 6]
console.log(arrPop); // 7

// 2.  Queue operation, first in first out
//   push()
//Shift(), deletes the first element from the array and returns the value of the element. This method changes the length of the array.
//Unshift(), adds one or more elements to the beginning of the array and returns the new length of the array (this method modifies the original array).
var arr = [1, 2, 3, 4, 5, 6];
var arrShift = arr.shift();
console.log(arr); // [2, 3, 4, 5, 6]
console.log(arrShift); // 1
arr.unshift(0,1);
console.log(arr); // [0, 1, 2, 3, 4, 5, 6]

// 3.  Operation method
//Concat() is used to combine two or more arrays. This method does not change the existing array, but returns a new array.
var arr1 = [0, 1, 2];
var arr2 = [4, 5, 6];
var arr3 = ['a', 'b', 'c', 'd']
var arr4 = arr1.concat(arr2, arr3);
console.log(arr4); // [0, 1, 2, 4, 5, 6, "a", "b", "c", "d"]

//Slice() intercepts a new array from the current array without affecting the original array. The parameters start from 0 and end from 1. Including start, excluding end.
var arr = [0, 1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd'];
var arrSlice = arr.slice(3, 6);
console.log(arrSlice); // [3, 4, 5]

//Splice(), delete or replace some items of the current array, parameters start, deletecount, options (items to be replaced)
var arr = [0, 1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd'];
arr.splice(5, 2, 's');
console.log(arr); // [0, 1, 2, 3, 4, 's', 'a', 'b', 'c', 'd']
arr.splice(5, 1);
console.log(arr); // [0, 1, 2, 3, 4, 'a', 'b', 'c', 'd']
arr.splice(-3, 2, 't');
console.log(arr); // [0, 1, 2, 3, 4, 't', 'd']

// 4.  Location method
//Indexof() returns the first index of a given element that can be found in the array. If it does not exist, it returns - 1
var arr = [0, 1, 2, 1, 4];
console.log(arr.indexOf(1)); // 1
console.log(arr.indexOf(1, 2)); // 3
console.log(arr.indexOf(1, -4)); // 1

//Lastindexof(), returns the index of the last specified element in the array. If it does not exist, it returns - 1 and looks up from back to front
var arr = [0, 1, 2, 1, 4];
console.log(arr.indexOf(1)); // 3
console.log(arr.indexOf(1, -3)); // 1
console.log(arr.indexOf(1, -4)); // 1

// 5.  The iterative method will not modify the original array. HTML5 has browser compatibility problems and can be used on the mobile terminal
//The every() method tests whether all elements in an array can pass the test of a specified function. It returns a Boolean value.
function fn1(currentValue) {
	return currentValue < 40;
}
function fn2(currentValue) {
	return currentValue < 100;
}
var fn3 = (currentValue) => currentValue < 95;
var arr = [2, 5, 2, 6, 3, 52, 95, 84, 25]
console.log(arr.every(fn1)); // false
console.log(arr.every(fn2)); // true
console.log(arr.every(fn3)); // true


//Filter (), creates a new array that contains all the elements of the test implemented by the provided function. 
function fn1(currentValue) {
	return currentValue < 40;
}
function fn2(currentValue) {
	return currentValue < 10;
}
var fn3 = (currentValue) => currentValue < 5;
var arr = [2, 5, 2, 6, 3, 52, 95, 84, 25]
console.log(arr.filter(fn1)); // [2, 5, 2, 6, 3, 25]
console.log(arr.filter(fn2)); // [2, 5, 2, 6, 3]
console.log(arr.filter(fn3)); // [2, 2, 3]

//Foreach(), executes the given function once for each element of the array.
function fn(currentValue) {
	return console.log(currentValue)
}
var arr = ['a', 'b', 'c', 'd', 'e']
arr.forEach(fn);

//Map(), creates a new array, and the result is the return value of each element in the array after calling the provided function once.
function fn(currentValue) {
	return currentValue += 10;
}
var arr = [0, 10, 20, 30, 40];
var arrMap = arr.map(fn);
console.log(arr); // [0, 10, 20, 30, 40]
console.log(arrMap); // [10, 20, 30, 40, 50]

//Some(), test whether at least one element in the array has passed the provided function test. It returns a value of type Boolean.
function fn(currentValue) {
	return currentValue % 10 === 0;
}
var arr = [3, 10, 22, 30, 40];
var arrSome = arr.some(fn);
console.log(arr); // [3, 10, 22, 30, 40]
console.log(arrSome); // true

// 6.  Concatenate all elements of the array into a string
//    join(),
Var arr = ['Zhang San', 'Li Si', 'Wang Wu', 'Xiao Ming', 'Xiao Hong']
var arrJoin1 = arr.join();
console. log(arrJoin1); // ' Zhang San, Li Si, Wang Wu, Xiao Ming, Xiao Hong '
var arrJoin2 = arr.join('|');
console. log(arrJoin2); // ' Zhang San, Li Si, Wang Wu, Xiao Ming, Xiao Hong '
//Simulate the internal implementation of join () method
function join(array, string) {
	var stringArr = array[0];
	for (var i = 1; i < array.length; i++) {
		stringArr += string + array[i];
	}
	return stringArr;
}
Var arr = ['Zhang San', 'Li Si', 'Wang Wu', 'Xiao Ming', 'Xiao Hong']
var stringArr = join(arr, '/');
console. log(stringArr); // ' Zhang San, Li Si, Wang Wu, Xiao Ming, Xiao Hong '

Sorting method of array

reverse()

Invert the position of the elements in the array and return the array. This method will change the original array

var arr = [1, 2, 3, 4, 5, 6];
arr.reverse();
console.log(arr);

sort()

  • Sorts the elements of the array and returns the array. The default sort order is built when converting elements to strings and then comparing their sequences of utf-16 code unit values
  • Syntax: arr.sort ([comparefunction])
  • Parameter: comparefunction (optional), used to specify the functions arranged in a certain order. If omitted, the elements are sorted according to the Unicode points of each character of the converted string.
  • Return value: sorted array
var arr = ["a", "F", "Adf", "Grew", "hef"];

//Without parameters, elements are sorted according to the Unicode sites of each character of the converted string.
arr.sort();
console.log(arr); // ["Adf", "F", "Grew", "a", "hef"]

//Sort by number size
var numberArr = [5, 58, 65, 2, 3, 5, 0, 84];
numberArr.sort(function (a, b) {
	return a - b;
});
console.log(numberArr); // [0, 2, 3, 5, 5, 58, 65, 84]

//Sort by string length
var stringArr = ["a", "F", "Adf", "Grew", "hef"];
stringArr.sort(function (a, b) {
	return a.length - b.length;
});
console.log(stringArr); // ["a", "F", "Adf", "hef", "Grew"]
//Simulate the internal implementation of sort () method
function sort(arr, compareFun) {
	for (var i = 0; i < arr.length; i++) {
		for (var j = 0; j < arr.length - 1 - i; j++) {
			if (compareFun(arr[j], arr[j + 1]) > 0) {
				var tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
	}
	return arr
}

var arr = [5, 10, 5, 68, 8, 6];
sort(arr, function (a, b) {
	return a - b;
});
console.log(arr);

Empty array

var arr = [1, 2, 5, 3, 5];
//The first method is recommended
arr = [];

//The second way
arr.length = 0;

//The third way
//The first parameter is where to delete the index
//Second parameter: how many elements are deleted
arr.splice(0, arr.length);

task

  1. Array of wages[1500, 1200, 2000, 2100, 1800], delete the salary exceeding 2000;
var arr = [1500, 1200, 2000, 2100, 1800];
var arr1 = arr.filter(function (item) {
	return item < 2000;
});
console.log(arr1);
  1. ['c', 'a', 'z', 'a', 'x', 'a']Find the position of each a in the array;
var arr = ['c', 'a', 'z', 'a', 'x', 'a'];
var index = -1;
do {
	index = arr.indexOf('a', index + 1);
	if (index !== -1) {
		console.log(index);
	}
} while (index !== -1)
  1. Write a method to remove the duplicate elements of an array;

6 linking methods:https://www.jb51.net/article/118657.htm

function repeat(arr) {
	var result = []
	for (var i = 0; i < arr.length; i++) {
		for (var j = i + 1; j < arr.length; j++) {
			if (arr[j] === arr[i]) {
				j = ++i;
			}
		}
		result.push(arr[i]);
	}
	return result
}
var arr = [1, 2, 1, 5, 2, 'a', 'b', 'a', 'b']
var arr1 = repeat(arr);
console.log(arr1);