JavaScript language Essentials five

He who knows others is wise, and he who knows himself is wise. He who conquers others is stronger than himself. – Lao tzu

Start:

An array is a linearly allocated chunk of memory, offset by integers, and access to its elements. An array is a highly performing data structure.

Array performance is superior at read time of O(1), array and linked list 👉 click

  • JavaScriptProvides some array-like objects (array-like).
  • Call: which subscripts the array to a string and uses it as a property.
  • Speed: It is significantly slower than arrays, but it has the advantage of being more convenient to use.
  • Retrieve and update: It works exactly like an object, except that multiple properties can use integers as property names.

Array literals

  • The literal approach provides a very simple notation for creating new arrays
    • Concept: Array literals are square brackets containing empty or multiple comma-delimited worthy expressions
    • Use: Can appear anywhere expressions are allowed
    • Hidden rule: the array starts with a property named ‘0’ and so on
  • Such as:
var container = [];
var nums = ["zero"."one"."two"."three"];
if (true) {
  container[1]; // undefined
  nums[1]; // one
  container.length; / / 0
  nums.length; / / 4
}
//- Object literals
var nums_object = {
  0: "zero".1: "one".2: "two".3: "three"};Copy the code
  • Both produce almost the same result
    • The similarities
      • nums å’Œ nums_objectBoth contain the same object
      • Their properties happen to have the same name and the same value
    • Distinction, master prototype chain of knowledge
      • numsInherited fromArray.prototype.nums_objectInherited fromObject.prototype
      • numsSpecific to alengthProperties, andnums_objectThere is no
    • Features – Most languages require that all elements of the same array be of the same type –JavaScriptAllows you to mix any type value you want

      Such as:

  var YaHu=[
    'poo'.233.false.null.undefined['compose1'.'compose2']
    {object:true}]Copy the code

The length of the

  • Arrays have a length property, but in JavaScript there is no limit to how long they can be.

  • If you store an element at a numeric index greater than the current array length, it will automatically expand

  • Added: language differences result in different restrictions on arrays 👉 click

  • Common sense:

    • inJavaScript,lengthProperty is independent of the number of current array properties
    • Its value is equal to the maximum integer property name of the current array +1
    • Set more than the number of array propertieslengthThe value does not allocate more memory to the array
    • Setting anything less than the number of array properties will remove all subscripts greater than or equal tolengthThe properties of the

  • You can also use an array fromArray.prototypeTo perform a series of operations on an array
    • For more frequently-used methods, click 👉

delete

  • JavaScriptThe array is also an object, so you can usedeleteOperator to remove an element from an array
  var arrs=['tomato'.'a cucumber'."Potato".'the eggplant']
  delete arrs[2]
    arrs[" tomato ", "cucumber "," empty ", "eggplant "]
Copy the code
  • As you can see, this method removes the specified element, but leaves a blank space
    • This is because deleting the element behind the current element will leave its original attributes unchanged, resulting in a gap
  • You can use a better solution, the array methodsplice
    • FirstPar is the ordinal of the index group, secondPar is the number of elements to delete, followed by arguments to insert elements after the ordinal
    • It removes a specific element and changes the properties of the element behind it
arrs.splice(2.1); // [" potato "]
arrs; // [" tomato ", "cucumber "," eggplant "]
Copy the code

The element after deleting changes because all the elements after deleting have to be inserted with the new key, so this method is inefficient when working with large arrays.

The enumeration

  • becauseJavaScriptThe array is actually an object
    • sofor inCan be used to traverse all attributes of a set
      • But this method can not guarantee its order, so there are great hidden dangers
    • While the use offorStatements can avoid these problems
      • 1. Initial loop; 2. 2. Perform conditional detection; 3. Incremental operations
    for(let i=0; i<arrs.length; i++){do something--
    }
Copy the code

Confusing areas

  • JavaScript, it’s easy to use an object when you have to use an array or vice versa
    • When attribute names are small, contiguous and integer, use arrays; otherwise, use objects
  • Because of language, injavascriptThe use oftypeofOperator to detect an array makes no sense
  • So to distinguish between arrays and objects, it’s usually availableconstructorCustom functions to solve the problem
    • constructorConstructor used to execute the current object
    • You can also call it without writing a functionArray.isArrayMethod to determine
function isArray(obj) {
    return obj && typeof(obj) === 'object' && obj.constructor === Array
}
Copy the code

An array of expansion

  • JavaScriptProvides a set of methods for using arrays stored in array.prototype.

    You can view dir(array.prototype) on the console

  • Whether it isObject.prototypeorArray.prototypeIt’s all scalable
  • So we can add a method to the array, to evaluate the array
 Array.methods('reduce'.function (f, value) {})//-- The book is given to write the above, I will rewrite it in the way I like
Array.prototype.fakereduce = function (fn, value) {
  for (let i = 0; i < this.length; i++) {
    value = fn(this[i], value)
  }
  return value;
}
let data = [1.2.4.6];
let sum = (a, b) = > {
  return a + b;
}
data.fakereduce(sum, 0)/ / 13
Copy the code

Methods set

javascriptContains a small set of methods that can be used on standard types

Array

array.concat(item)

  • concatMethod generates a new array containing aarrayShallow copy of (shallow copy)
  • And put the backitemAppend to an array, ifitemIs an array, its elements are added separately.
let arr1 = ["first"."second"];
let arr2 = ["zero"."one"];
let newArr = arr1.concat(arr2, "flag");
// [ 'first', 'second', 'zero', 'one', 'flag' ]
Copy the code

array.join(separator)

  • joinMethod to put aarrayConstruct a string
    • It firstarrayEach element is constructed as a string
    • Then use theseparatorDelimiters are concatenated, defaultseparatorIs a comma
    • You can use Spaces instead of commas
let arr1 = ["first"."second"];
let arr2 = ["zero"."one"];
let newArr = arr1.join(); // first,second
let newArr2 = arr2.join(""); // zeroone
Copy the code
  • array.push(item...)
    • pushMethod to put one or moreitemAttached to the end of an array
    • (withconcatThe difference is, it changes the array )
      • If the argument is an array, add the entire array to the original array (not one by one) and returnarrayThe new length value of
let arr1 = ["first"."second"];
let arr2 = ["| |"];
let arr3 = ["cherry"."watermelon"];
let newArr1 = arr1.push(arr2, "flag");
arr1; // [ 'first', 'second', [ '||' ], 'flag' ]
newArr1; / / 4
let newArr2 = arr1.push(arr3);
arr1; //[ 'first', 'second', [ 'cherry', 'watermelon' ] ]
newArr2; / / - 3
Copy the code

array.reverse()

  • reverseThe method is reversedarrayAnd returns itself;
let arr = ["first"."second"."third"];
let revArr = arr.reverse();
console.log(revArr); // [ 'third', 'second', 'first' ]
Copy the code

array.shift()

  • shiftThe () method removes the first element from the array and returns that element;
  • If the array is empty, this method returnsundefined
  • (Usually,shift 比 popMuch slower)
let arr = ["first"."second"."third"];
let revArr = arr.shift();
console.log(revArr); // first
/* This method can be implemented manually */
Array.prototype.fakeShift = function () {
  return this.splice(0.1) [0];
};
var revArr2 = arr.fakeShift();
console.log(revArr2); // second
Copy the code

array.slice(star,end)

  • sliceThe () method makes a shallow copy of the specified segment of the array;
    • fromarray[star]Copied to thearray[end]
    • endIs not required. The default value is the length of the current array
    • If either parameter is negative, it is added to the length of the array in an attempt to reverse it
    • ifstarValue greater than the length of the array, a new, empty array is returned
let arr = ["first"."second"."third"."fourth"];
// let revArr = arr.slice(1,2); // [ 'second' ]
// let revArr = arr.slice(1,-2); // [ 'second' ]-- -2+4=2
// let revArr = arr.slice(-3,2); // [ 'second' ]-- -3+4=1
Copy the code

array.sort(comparefn)

  • sortThe sort () method sorts the contents of an array, but cannot be used to sort a set of numbers;
  • Because the default element is a string to compare, the sort is often wrong.
  • Sort the elements of an array alphabetically, or more precisely, by character encoding

    To quote – W3school

let arr1 = ["14"."3"."Seven"."11"];
let arr2 = ["d"."c"."a"."x"];
arr1.sort();
arr2.sort();
console.log(arr1); // ['11', '14', '3', '7']
console.log(arr2); // [ 'a', 'c', 'd', 'x' ]
Copy the code
  • The remedy is to add a comparison function
    • If a is less than b, and a should come before b in the sorted array, return a value less than 0.
    • If a is equal to b, return 0.
    • If a is greater than b, return a value greater than 0.

      To quote – W3school

let arr3 = ["14"."3"."Seven"."11"];
arr3.sort(function (a, b) {
  return a - b;
});
console.log(arr3); // ['3', '7', '11', '14']
Copy the code
  • The change solves sorting for pure numbers, but does not apply to arguments of string type
    • Then consider the array of impure numbers in the function, and make the following corrections
var arr4 = ["b"."r".14."a".3.7.11];
arr4.sort(function (a, b) {
  if (a === b) return 0;
  if (typeof a === typeof b) return a - b ? -1 : 1;
  return typeof a < typeof b ? -1 : 1;
});
console.log(arr4); // [ 3, 7, 11, 14, 'a', 'b', 'r' ]
Copy the code

array.splice(star,deleteCount,item..)

  • spliceMethod removes one or more elements from the array and converts the newitemMake the substitution.
    • starThis is where the element is removed from
    • deleteCountIt’s the number of things you remove
    • Additional arguments, if any, are inserted by default at the location where the element was removed
var arr4 = ["Wang Hua Hua"."Zhao Guangguang"."Li Foot"];
arr4.splice(1.1."Beautiful Sun");
console.log(arr4); // [' Wang Huahua ', 'Sun Meili ',' Li Foot ']
Copy the code

array.unshift(item..)

  • unshiftMethods theitemInsert into the beginning of the array and return the new length of the array
var arr5 = ["Wang Hua Hua"."Zhao Guangguang"."Li Foot"];
arr5.unshift("Beautiful Sun");
console.log(arr5); //[' Sun Meili ', 'Wang Huahua ',' Zhao Guangguang ', 'Li Foot']
Copy the code

unshiftThe method can be implemented as follows

var arr6 = ["Wang Hua Hua"."Zhao Guangguang"."Li Foot"];
Array.prototype.fakeunshift = function () {
  this.splice.apply(
    this[0.0].concat(Array.prototype.slice.apply(arguments)));return this.length;
};
arr6.fakeunshift("Beautiful Sun");
console.log(arr6); //[' Sun Meili ', 'Wang Huahua ',' Zhao Guangguang ', 'Li Foot']
Copy the code

Conclusion:

This chapter describes some of the core and common knowledge of arrays in JavaScript. I have hand-written some examples and personal summary, and also removed some of the regular-related knowledge (because the time/gain ratio is too low) because of the amount of content. Arrays are divided into a separate chapter and summarized in the next chapter. Features such as Function, Number, String, and Object

You may also be interested in the following

  • # JavaScript Language Essentials 1 (simple lab)
  • Everything is an Object
  • # JavaScript Language Essentials 3 (Core — functions)
  • # JavaScript Language Essence 4 (Inheritance)
  • # JavaScript language Essence 6 (JS method set)
  • How are some of the apis implemented in # VUE3.0?
  • JavaScript reads local file configuration (compatible with lower IE versions)
  • # What do you ask about the front end of one year’s work experience?