The sea is wide by diving, the sky is high as birds fly. Hey how are you! I’m Ed Qin. 😄

Recently, SEVERAL of my friends and I organized a student union with excellent performance, and agreed to hold a technology sharing meeting every weekend (volume conference, which has been in the fifth phase). This post is shared by our alliance partner Hage 😎 😎 😎

preface

Arrays, the most basic one-dimensional data structure, play such a crucial role in all kinds of programming languages that it’s hard to imagine a programming language without arrays. JavaScript, in particular, takes advantage of arrays with its inherent flexibility and enriches their usage scenarios. It’s no exaggeration to say that you can’t write JavaScript well without a deep understanding of arrays.

As front-end frameworks evolve and MVVM frameworks such as React and Vue become popular, views are updated as data is updated. In a large number of business code implemented through the front-end framework, developers will use arrays to store data and various operations such as “add, delete, change and check”, so as to realize the update of the corresponding front-end view layer. Therefore, it is necessary to master various methods of array and have a deep understanding of array.

So, before we start, let me ask you a few questions.

  1. What kinds of array constructors are there?

  2. What are the ways to change yourself?

  3. What are the ways of not changing yourself?

  4. What are the methods of traversal?

An exploration of array concepts

As of the ES7 specification, the array contains 33 standard API methods and one non-standard API method, and the usage scenarios and use schemes are complicated, among which there are many pits. To make it easier for you to learn this part step by step, I’m going to start with the concept of arrays.

Since there are a lot of array apis, many similar names can be confusing, so I’m going to separate them into three types: “self-changing”, “non-self-changing”, and “traversal methods” to give you a more structured view of these apis. ,,,

Constructor for Array

The Array constructor is used to create a new Array. In general, it is recommended to create an array using object literals, such as var a = []. However, there are always times when object literals are weak. For example, I want to create an empty array of length 6, which cannot be created using object literals, so I have to write the following code.

Let a = Array(3); //[empty * 3] // let b = []; b.length = 3; //[undefined * 3]Copy the code

The Array constructor does two different things, depending on the length of the argument:

New Array (arg1, arg2,…). , when the parameter length is 0 or greater than or equal to 2, the passed parameter will become the 0th to the NTH item of the new array in sequence (when the parameter length is 0, an empty array is returned);

New Array(len), if len is not a number, returns an Array containing only one len element; When len is numeric, len must be no more than a 32-bit unsigned integer, that is, less than 2 to the power of 32 (len is at most math.pow (2,32)), otherwise a RangeError will be raised.

That’s the basic Array constructor, but let’s take a look at some of the new constructors in ES6.

New constructors in ES6: array. of and array. from

Array.of

Array.of is used to convert arguments to one item in an Array and then return the new Array, regardless of whether the argument is numeric or otherwise. It basically functions the same as the Array constructor, the only difference being the handling of a single numeric parameter.

An Array of (2.0); / / [2] Array (2.0); //[empty * 2] array.of (2.0, 3); / / [2, 3] Array (2.0, 3); //[2, 3] Array.of('8'); //["8"] Array('8'); / / [8]Copy the code

Array.from

Array.from is designed to be a quick and easy way to create new arrays based on other objects, specifically a new Array instance from an array-like iterable. As long as an object has an iterator, array. from turns it into an Array (note: it returns the new Array, not the original object).

Syntactically, array. from takes three arguments:

  1. An array-like object, mandatory.

  2. Processing function, the newly generated array will be processed by the function and then returned;

  3. This scope, which represents the value of this when the processing function executes.

Let obj = {0: 'pig's feet ', 1:' pig's feet ', 2: 'beer ', length: 3}; Array.from(obj, function(value, index){ console.log(value, index, this, arguments.length) return value; // return value must be specified, otherwise return undefined, obj);Copy the code

The results are shown below:

This shows that the array. from method allows you to define what the processing function does to return the desired value; If the return value is uncertain, undefined is returned, resulting in an empty array containing undefined elements.

In fact, if this is not specified here, the processing function could be an arrow function at all. The above code can be abbreviated as follows.

Array.from(obj, (value, index) => value)Copy the code

In addition to obj, objects with iterators include strings, sets, maps, etc. Array.from can be handled, as shown in the code below.

//String
Array.from('abc');   //["a", "b", "c"]

//Set
Array.from(new Set(['a', 'b']));   //["a", "b"]

//Map
Array.from(new Map([['a'], ['b']]));   //[["a"], ["b"]]
Copy the code

An Array of judgment

Before ES5 provided this method, there were at least five ways to determine if a variable was an array.

let a = []; // 1. Instanceof Array; // 2. Constructor === Array; / / 3. Based on the Object. The prototype. IsProtoTypeOf Array. The prototype. IsProtoTypeOf (a); GetProtoTypeOf (a) === array. prototype // 5. Based on the Object. The prototype. ToString Object. The prototype. ToString (a) = = = '[Object Array]'Copy the code

All five of the above statements are True.

IsArray () : array. isArray () : array. isArray () : array. isArray () : array. isArray ();

if(! Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]' } }Copy the code

Now that we’ve covered the basics of arrays, let’s take a look at some of the more than 30 basic methods for bewildering arrays.

Ways to change yourself

Based on ES6, there are nine methods that change their values: POP, Push, Reverse, Shift, sort, splice, unshift, and two new ES6 methods, copyWithin and Fill.

/ / pop method var array = [" cat ", "dog", "cow", "chicken", "mouse"]. var item = array.pop(); console.log(array); // ["cat", "dog", "cow", "chicken"] console.log(item); Var array = ["football", "basketball", "badminton"]; var i = array.push("golfball"); console.log(array); // ["football", "basketball", "badminton", "golfball"] console.log(i); Var array = [1,2,3,4,5]; var array2 = array.reverse(); console.log(array); / /,4,3,2,1 [5] the console. The log (array2 = = = array); Var array = [1,2,3,4,5]; var item = array.shift(); console.log(array); / / 5-tetrafluorobenzoic [2] the console log (item); Var array = ["red", "green", "blue"]; var length = array.unshift("yellow"); console.log(array); // ["yellow", "red", "green", "blue"] console.log(length); / / 4 / var/sort method array = [" apple ", "Boy", "Cat", "dog"); var array2 = array.sort(); console.log(array); // ["Boy", "Cat", "apple", "dog"] console.log(array2 == array); // true // splice () var array = ["apple","boy"]; Var splices = array. Splice (1, 1); console.log(array); // ["apple"] console.log(splices); / / / "boy"/var/copyWithin method array = [1, 2, 3, 4, 5]; Var array2 = array. CopyWithin (0, 3); console.log(array===array2,array2); / / true [4, 5, 3, 4, 5] / / the fill method of var array = [1, 2, 3, 4, 5]; Var array2 = array. The fill (10,0,3); console.log(array===array2,array2); // true [10, 10, 10, 4, 5], all elements in the range [0,3] are replaced by 10Copy the code

Don’t change your ways

Based on ES6, there are also 9 methods that will not change themselves, namely concat, Join, slice, toString, toLocaleString, indexOf, lastIndexOf, and toSource that has not formed a standard. And the new method includes in ES7.

Var array = [1, 2, 3]; Var array2 = array concat (4, 5, 6], [7,8,9]); console.log(array2); // [1, 2, 3, 4, 5, 6, 7, 8, 9] console.log(array); Var array = ['We', 'are', 'Chinese']; console.log(array.join()); // "We,are,Chinese" console.log(array.join('+')); / / "We are + + Chinese"/var/slice method array = [" one ", "two", "three", "four", "five"]. console.log(array.slice()); / / [" one ", "two", "three", "four", "five"] the console. The log (array) slice (2, 3)); / / / "three"/var/toString method array = [' Jan, Feb, Mar, Apr ']. var str = array.toString(); console.log(str); Var array= [{name:'zz'}, 123, "ABC ", new Date()]; var str = array.toLocaleString(); console.log(str); Var array = [' ABC ',' def', 'ghi','123']; var array = [' ABC ',' def', 'ghi','123']; console.log(array.indexOf('def')); // 1 // includes method var array = [-0, 1, 2]; console.log(array.includes(+0)); // true console.log(array.includes(1)); // true var array = [NaN]; console.log(array.includes(NaN)); // trueCopy the code

Array traversal method

Based on ES6, there are 12 traversal methods that will not change themselves, which are forEach, every, some, Filter, Map, reduce and reduceRight. And ES6 new methods Entries, find, findIndex, keys and values.

Var array = [1, 3, 5]; var obj = {name:'cc'}; var sReturn = array.forEach(function(value, index, array){ array[index] = value; console.log(this.name); // cc is printed three times, this points to obj},obj); console.log(array); // [1, 3, 5] console.log(sReturn); Var o = {0:10, 1:8, 2:25, length:3}; var bool = Array.prototype.every.call(o,function(value, index, obj){ return value >= 8; },o); console.log(bool); Var array = [18, 9, 10, 35, 80]; var isExist = array.some(function(value, index, array){ return value > 20; }); console.log(isExist); Var array = [18, 9, 10, 35, 80]; array.map(item => item + 1); console.log(array); Var array = [18, 9, 10, 35, 80]; var array2 = array.filter(function(value, index, array){ return value > 20; }); console.log(array2); // [35, 80] // Reduce method var array = [1, 2, 3, 4]; var s = array.reduce(function(previousValue, value, index, array){ return previousValue * value; }, 1); console.log(s); Array. reduce((p, v) => p * v); // 24 // reduceRight (reduceRight) var array = [1, 2, 3, 4]; array.reduceRight((p, v) => p * v); // 24 // entries method var array = ["a", "b", "c"]; var iterator = array.entries(); console.log(iterator.next().value); // [0, "a"] console.log(iterator.next().value); // [1, "b"] console.log(iterator.next().value); // [2, "c"] console.log(iterator.next().value); Find & findIndex var array = [1, 3, 5, 7, 8, 9, 10]; function f(value, index, array){ return value%2==0; } function f2(value, index, array){return value > 20; } console.log(array.find(f));} console.log(array.find(f)); // 8 console.log(array.find(f2)); // undefined console.log(array.findIndex(f)); // 4 console.log(array.findIndex(f2)); Keys [...Array(10).keys()]; // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [...new Array(10).keys()]; / / [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] / / var array values method = (" ABC ", "xyz"); var iterator = array.values(); console.log(iterator.next().value); //abc console.log(iterator.next().value); //xyzCopy the code

Note that some traversal methods do not return the array after processing, such as forEach; Some methods return the array after processing, such as filter.

Above, the basic explanation of each array method is finished, there are many commonalities between these methods, as follows:

  • All the methods of inserting elements, such aspush,unshiftAlways return the new length of the array;
  • All methods to delete elements, such aspop,shift,spliceReturn all deleted elements, or an array of deleted elements;
  • Partial traversal methods, such asforEach,every,some,filter,map,find,findIndex, they all containfunction(value,index,array){} å’Œ thisArgThese two parameters.

Thank you

Welcome to pay attention to my personal public number front Qin Aide every day to push you fresh quality good article. Reply “benefits” and you will get my carefully prepared front-end knowledge gift package. May you go all the way with light in your eyes!

Interested partners can also add my wechat: WebQinaid to exchange front-end technology and play together!

Phase to recommend

I developed a chrome plugin to remind you to drink water.

Come on! Talk with Ed Qin about “problems” at work

A perennial question, what is object orientation?