The use of javascript high-frequency methods

array

There are many methods of arrays. Although they can be found in this era of the Internet, the common methods should be used smoothly for the sake of development efficiency. We will not go into details about some common methods such as push.

1. join (do not change the original array)

? This method can connect the elements in the array in the form of strings through the specified separator.

//Convert the array to a string, separated by spaces
let arr = [1,2,3,4,5];
let str = arr. join(' ');
console.log(str) // 1 2 3 4 5

The method of converting strings to arrays that is easily confused with join, and split is easy to remember.

let str = 'wqz-ttj';
let arr = str. split('-');
console.log(arr);// arr=['wqz','ttj'];

2. reverse Flip the array (change the original array)

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

3. sort (change the original array)

let arr = [1,3,5,2,4,23,122,34];
//No parameter: sort according to the order of the first character
arr.sort()//arr=[1,122,2,23,3,34,4,5];
// have parameters
let a = arr. sort(function(a,b){
return a-b;//Sort from small to large
// return b-a;//Sort from big to small
})

console.log(a); //[ 1, 2, 3, 4, 5, 23, 34, 122 ]

4. concat merge array (do not change the original array)

let arr = [1,2,3,4,5]
let arr1 = [2,3,3,4,5]
let arr2 = arr1.concat(arr)


console.log(arr); // [ 1, 2, 3, 4, 5 ]
console.log(arr1); // [ 2, 3, 3, 4, 5 ]
console.log(arr2); // [ 2, 3, 3, 4, 5, 1, 2, 3, 4, 5 ]

5. slice array interception (do not change the original array)

// arr.slice(start, end) ; start to intercept from the subscript of start until the end of end, excluding end

let arr = [0,1,2,3,4,5,6,7];
let newArr = arr. slice(0,3)//newArr = [0,1,2];


// arr.slice(start) ; intercept from the start subscript until the end

let arr = [0,1,2,3,4,5,6,7];
let newArr = arr. slice(2)//newArr = [2, 3, 4, 5, 6, 7];

// arr.slice ( ) ; all intercepted

let arr = [0,1,2,3,4,5,6,7];
let newArr = arr. slice()//newArr = [0,1,2,3,4,5,6,7];

6. splice interception (change the original array)

let arr = [1,2,3,4,5]
// Structure 1: arr.splice(start,deletedCount) pure deletion
// Starting from the start subscript, delete a few
// arr.splice(0,2)
// console. log(arr); // [ 3, 4, 5 ]

// Structure 2: arr.splice(start,deletedCount,item) replacement
// Starting from the start subscript, delete a few, and add item at this position
// arr.splice(0,2,7)
// console. log(arr); // [7, 3, 4, 5 ]

// Structure 3: arr.splice(start,0,item) pure addition
// Start from the start subscript, delete 0, and add item at this position, start all move backward
arr.splice(0,0,7,8,9)

console.log(arr); // [ 7, 8, 9, 1, 2, 3, 4, 5 ]

7. map / forEach / filter

forEach : This method is equivalent to a for loop and has no return value
arr.forEach(function(item,index,arr){
//The function inside is a callback function,
//item: each item in the array;
//index: the subscript index value corresponding to the item
//arr: is the array itself that calls the method
})

map mapping, this method is roughly the same as forEach, but this method has a return value, returns a new array, and the length of the new array is equal to the length of the original array

let arr = [1,32,54,6,543];
let res = arr. map(function(item,index,arr){
return item*2;
})
filter method: with a return value, filter out elements that meet the conditions

let arr2 = [0, "", false, 1, 3, 4];
let res4 = arr2. filter(item => item != 1)
console.log(res4);

8. find / findIndex

//find
Find the item that meets the criteria and return the first item
let arr4 = [
    { id: 3, name: "ls", done: false },
    { id: 1, name: "zs", done: true },
    { id: 2, name: "ww", done: true }
  ];
  var res7 = arr4. find(function(item) {
    return item.id == 2;
  });
  console.log(res7); { id: 2, name: 'ww', done: true }

// findIndex
var res8 = arr4. findIndex(function(item) {
    return item.name == 'ww';
  });
  console.log(res8); // 2 index
  

9. redux

1. Sum calculation

1: pre = 1 ; next = 1; 2
2: pre = 2; next = 2; 4
3: pre = 4; next = 3; 7
4: pre = 7; next = 4; 11
5: pre = 11 ; next = 5; 16


var arr1 = [1,2,3,4,5];
var new1 = arr1. reduce(function(pre,next,index){
return pre + next ;
},1) // 1 represents the first pre
console. log(new1);
\t

10. some / every

// some: Determine whether there are eligible items in the array (as long as there is, return true), if there is none, return false
// every: Determine whether all items in the array meet the requirements, if all are met, return true, otherwise return false

let arr3 = [
    { name: "zs", age: 18, done: false },
    { name: "ls", age: 20, done: true },
    { name: "ww", age: 22, done: true }
  ];
  let res5 = arr3. some(function(item) {
    return item. done;
  });
  console.log(res5);

let res6 = arr3. every(function(item) {
  return item. done;
});
console.log(res6);

11. indexof / lastIndexof find element position

// indexOf This method is used to find the position where the element appears for the first time in the array
// lastIndexOf This method is used to find the position where the element last appeared in the array
arr.indexOf(element, start from that subscript)

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

console.log(arr.indexOf(7)); // returns -1 if it does not exist

// Check if the element exists in the array
if(arr. indexOf(x) == -1){
    console.log(does not exist);
}else{
    console.log(exist);
}

Object

1. Object. keys()

Will return an array including the names of all enumerable own properties (Object.getOwnPropertyNames returns whether it is enumerable or not)

const arr = ['a', 'b', 'c']
 
console.log(Object.keys(arr)) // ['0', '1', '2']
 
const obj = { 0: 'a', 1: 'b', 2: 'c' }
 
console.log(Object.keys(obj)) // ['0', '1', '2']
 
const obj2 = { 100: 'a', 2: 'b', 7: 'c' }

// If the object key is number, it will be returned from the ascending enumeration.
console.log(Object.keys(obj2)) // ['2', '7', '100']


const obj2 = { 100: 'a', 2: 'b', 7: 'c' }

Object.defineProperty(obj2, 100 , {
    enumerable: false
})

console.log(Object.keys(obj2)) // [ '2', '7' ] // enumerable
console.log(Object.getOwnPropertyNames(obj2)); //[ '2', '7', '100' ] // Whether it is enumerable or not

2. Object. assign()

Syntax:

Object.assign(target, ...sources)
 
// Parameters: target target parameter, sources source object Return value: target object

The Object.assign() method is used to assign the values of all enumerable properties from one or more source objects to a target object. It will return the target object. Often used to combine objects.

const obj1 = { a: 1, b: 2 }
 
const obj2 = { b: 4, c: 5 }
 
const obj3 = Object. assign(obj1, obj2)
 
const obj4 = Object.assign({}, obj1) // cloned obj1 object
 
console.log(obj1) // { a: 1, b: 4, c: 5 } replaces the attribute b with the same name. obj1 changes because obj2 is assigned to obj1
 
console.log(obj2) // { b: 4, c: 5 }
 
console.log(obj3) // { a: 1, b: 4, c: 5 }
 
console.log(obj4) // { a: 1, b: 4, c: 5 }

//assign is actually a shallow copy rather than a deep copy. That is to say, if the value of a property of the source object is an object, then the copy of the target object gets a reference to this object. Properties with the same name are replaced.

const obj5 = { a: 1, b: { c: 4, d: 5 } }

const obj6 = { a: { c: 1 } }

const obj7 = Object. assign(obj5, obj6)

console.log(obj7); // { a: { c: 1 }, b: { c: 4, d: 5 } }

obj6.a.c = 2

console.log(obj7); // { a: { c: 2 }, b: { c: 4, d: 5 } }

3. Object. values

Syntax:

Object.values(obj)

The Object.values() method returns an array of all enumerable property values of a given object itself, similar to Object.keys() , the difference is that this returns the value of the data, which is value

const obj1 = { foo: 'bar', baz: 42 }
console.log(Object.values(obj1)) // ['bar', 42]
 
const obj2 = { 0: 'a', 1: 'b', 2: 'c' }
console.log(Object.values(obj2)) // ['a', 'b', 'c']

4. Object. entries(obj)

Syntax:

Object.entries(obj)

The Object.entries() method returns an array of key-value pairs for a given object’s own enumerable properties.

const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
 
// array like object object like array
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
 
// array like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
// The return value will be sorted in ascending order by key
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]

//ES2015 new will force non-object parameters into objects
console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]

Application: Use this method to convert Object to Map

const obj = { foo: "bar", baz: 42 }
const map = new Map(Object. entries(obj))
console.log(map) // Map { foo: "bar", baz: 42 }

5. Object. fromEntries()

Syntax:

Object. fromEntries(iterable)

The Object.fromEntries() method converts a list of key-value pairs into an object. The opposite of Object.entries(). It is equivalent to reversing the data structure returned by the Object.entries() method.

1. Convert Map to Object

const map = new Map([ ['foo', 'bar'], ['baz', 42] ])
const obj = Object. fromEntries(map)
console. log(obj)
// { foo: "bar", baz: 42 }

2. Convert Array to Object

const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
const obj = Object. fromEntries(arr)
console. log(obj)
// { 0: "a", 1: "b", 2: "c" }

3. Multiply the value of the object by 2

// what most people do
const obj2 = {a:1,b:2,c:3}

for (let key in obj2) {
  obj2[key] = obj2[key] * 2
}

console.log(obj2);


// Use the fromEntries / entries method

const object2 = Object. fromEntries(
  Object.entries(object1)
  .map(([ key, val ]) => [ key, val * 2 ])
)
 
// Object.entries(object1) >>> [["a",1],["b",2],["c",3]]
 
console.log(object2) // { a: 2, b: 4, c: 6 }

6. Object.prototype.hasOwnProperty()

hasOwnProperty() The method will return a Boolean value, indicating whether the object has the specified property in its own properties. It will only judge its own properties, and all inherited properties will return false. Used with for...in, it can avoid traversing inherited properties.

Application: Handwritten shallow copy

function shallowCopy(target) {
  // The reference type needs to open up a new storage address
  if (typeof target === 'object' & amp; & amp; target !== null) {
    const copy = Array.isArray(target) ? [] : {}
    for (const prop in target) {
      if (target. hasOwnProperty(prop)) {
        copy[prop] = target[prop]
      }
    }
    return copy
  }
  // If it is a basic type, return directly
  return target
}

This article summarizes the js methods we commonly use in development. Although the methods are very basic, it is very helpful for us to improve the development efficiency by using these methods proficiently.