preface

This article is a summary of common methods for arrays, strings, and objects. Refer to the article at the end.

An array of

Create an array

Literal creation

Var a = [3, 11, 8]; var a = [3, 11, 8]; / /,11,8 [3];Copy the code

Constructor creation

// New Array === Array. var a = Array(); // [] var a = Array(3); // [,,] var a = Array(3,11,8); / /,11,8 [3]Copy the code

ES6 Array.of

Definition: Returns an array of all parameter values, or an empty array if there are no parameters.

Purpose: Array.of() is used to solve the problem that the constructor behaves differently due to the number of arguments

let a = Array.of(3, 11, 8); // [3,11,8] let a = array.of (3); / / [3]Copy the code

ES6 Array,from

Definition: Used to convert two types of objects into true arrays (return new arrays without changing the original objects).

Parameters:

First argument (required): the object to be converted to a true array.

Second argument (optional): An array-like map method that processes each element and puts the processed value into the returned array.

The third argument (optional) is used to bind this.

/ / 1. The object has length attribute let obj = {0: 'a', 1: 'b', 2: 'c', length: 3}; let arr = Array.from(obj); // ['a','b','c']; // 2. Data structures with Iterator interfaces such as strings, sets, NodeList objects let arr = array. from('hello'); // ['h','e','l','l','o'] let arr = Array.from(new Set(['a','b'])); // ['a','b']Copy the code

Change the original array

Let a = [1, 2, 3]; ES5: a.splice()/ a.sort() / a.pop()/ a.shift()/ a.push()/ a.unshift()/ a.reverse() ES6: a.copyWithin() / a.fillCopy the code

For these methods that can change the array, it is important to avoid options that change the array during the loop, such as changing the length of the array, resulting in length problems.

Pop () removes the last element of the array

Definition: The pop() method removes the last element in an array and returns that element.

Parameters: no

Let a = [1, 2, 3]; let item = a.pop(); // 3 console.log(a); / / [1, 2]Copy the code

Shift () removes the first element of the array

Definition: The shift() method removes the first element of an array and returns it.

Parameter: None.

Let a = [1, 2, 3]; let item = a.shift(); // 1 console.log(a); / / [2, 3]Copy the code

Push () adds elements to the end of the array

Definition: The push() method adds one or more elements to the end of an array and returns a new length.

Parameters: item1, item2… ItemX, the element to be added to the end of the array

Let a = [1, 2, 3]; Let item = a.push(' end '); // 4 console.log(a); // [1,2,3,' end ']Copy the code

Unshift () adds elements to the head of the array

Definition: The unshift() method adds one or more elements to the beginning of an array and returns the new length.

Parameters: item1, item2… ItemX, the element to be added to the beginning of the array

Let a = [1, 2, 3]; Let item = a.nshift (' start '); // 4 console.log(a); // [' start ',1,2,3]Copy the code

Splice () adds and deletes elements

Definition: a splice () method to/from add/remove programs in the array, and then return the deleted project syntax: array. The splice (index, howmany, item1,… , itemX) parameters:

Index: required. Integer to specify where items are added/removed, and negative numbers to specify positions from the end of the array. Howmany: Optional. Number of items to delete. If set to 0, the project will not be deleted. item1, … , itemX: Optional. The new item added to the array.

Return value: Returns a new array containing the deleted item if any elements have been deleted.

Eg1: Deletes elements

let a = [1, 2, 3, 4, 5, 6, 7]; let item = a.splice(0, 3); / / [1, 2, 3]. The console log (a); Let item = a.ice (-1, 3); let item = a.ice (-1, 3); // [7] // Remove 3 elements from the last element, only 7 is removed because of the last elementCopy the code

Eg2: Delete and add

let a = [1, 2, 3, 4, 5, 6, 7]; Let item = a.ice (0,3,' add '); / / [1, 2, 3]. The console log (a); / / / / [' add ', 4, 7] from the array subscript 0, delete three elements, and add the elements' add 'let b = [1, 2, 3, 4, 5, 6, 7]. Let item = b.ice (-2,3,' add 1',' add 2'); / / [6, 7]. The console log (b); // [1,2,3,4,5,' Add 1',' Add 2'] // From the last second element of array, delete 3 elements, and add 2 elements' Add 1',' add 2'Copy the code

Eg3: Does not delete but adds:

let a = [1, 2, 3, 4, 5, 6, 7]; Let item = a.splice(0,0,' add 1',' add 2'); // [] Returns empty array console.log(a) without deleting elements; / / / 'add 1', 'added 2', 1,2,3,4,5,6,7] let b = [1, 2, 3, 4, 5, 6, 7]. Let item = b.ice (-1,0,' add 1',' add 2'); // [] Returns empty array console.log(b) without deleting elements; // [1,2,3,4,5,6,' Add 1',' Add 2',7] Adds two elements before the last elementCopy the code

It can be concluded from the above three chestnuts:

If there are not enough elements in the array, it will delete the elements up to the last element, including the element at the beginning and you can add a lot of elements before you add the element at the beginning

Reverse () flips the array

Definition: The reverse() method is used to reverse the order of elements in an array.

Parameters: no

Let a = [1, 2, 3]; a.reverse(); console.log(a); / / [3, 2, 1]Copy the code

Sort () sort an array

Definition: The sort() method sorts the elements of an array and returns the array.

Parameter Optional: Comparison function that specifies the sort order.

By default, if sort() does not pass a comparison function, it defaults to an alphabetical ascending order. If it is not an element that is not a string, the toString() method is called to convert the element to the Unicode point of the string, and then the characters are compared.

Var a = ["Banana", "Orange", "Apple", "Mango"]; a.sort(); // ["Apple","Banana","Mango","Orange"] Some of the numbers are going to be bigger than others and that's not what we want var a = [10, 1, 3, 20,25,8]; The console. The log (a.s ort ()) / /,10,20,25,3,8 [1];Copy the code

ES6 Fill () fills the array

Definition: Fills an array with the given value.

Parameters:

First element (required): the values to populate the array

Second element (optional): the start of the fill, default is 0

Third element (optional) : the end of the fill, default is this.length

MDN browser compatible

['a', 'b', 'c'].fill(7)
// [7, 7, 7]
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
Copy the code

ES6 CopyWithin specifies the location where the element is copied to another location

Definition: Copies a member of the specified location to another location inside the current array and returns the array.

Grammar:

array.copyWithin(target, start = 0, end = this.length)
Copy the code

Number: All three parameters are numeric values. If they are not, they are automatically converted to numeric values.

Target (required) : Replace data from this location. If it is negative, it is the reciprocal. Start (Optional) : reads data from this position. The default value is 0. If it is negative, it is the reciprocal. End (Optional) : Stops reading data until this position, which is equal to the array length by default. Use negative numbers to specify positions from the end of the array.

Browser compatibility (MDN): chrome 45,Edge 12,Firefox32,Opera 32,Safari 9, IE not supported eg:

// Select * from *; 1 of 4 [1, 2, 3, 4, 5]. CopyWithin (0, 2, 1) / / [4, 2, 3, 4, 5] var a = [' OB1 ', 'Koro1', 'OB2', 'Koro2', 'OB3', 'Koro3', 'OB4', 'Koro4', 'OB5', 'Koro5'] / / 2 position began to be replaced, 3 start reading to replace 5 location stop in front of the replacement A.c opyWithin,3,5 (2) / / [" OB1, "" Koro1", "Koro2", "OB3," "OB3," "Koro3", "OB4", "Koro4", "OB5", "Koro5"]Copy the code

From the chestnuts above:

The first argument is the position of the element to be replaced: the second argument is the element to be read, and before the third argument an element stops reading the length of the array does not change. After reading several elements, several elements are replaced from where they were replaced

Do not change the original array

Join () array to string

Definition: The join() method is used to separate all the elements of an array into a string with the specified delimiter and return the generated string.

Grammar:

array.join(str)
Copy the code

Parameters:

STR (optional): Specifies the delimiter to use. By default, commas are used as delimiters

let a= ['hello','world'];
let str=a.join(); // 'hello,world'
let str2=a.join('+'); // 'hello+worl
Copy the code

When using the Join method or the toString method described below, what happens when the elements of an array are also arrays or objects?

let a= [['OBKoro1','23'],'test']; let str1=a.join(); / / OBKoro1, 23, test the let b = ({name: 'OBKoro1, age:' 23 '}, 'test']. let str2 = b.join(); // [object object],test // Object to string recommended json.stringify (objCopy the code

Therefore, join()/toString() calls join()/toString() when an array element is an array, and the object is converted to an object object string if it is an object.

ToLocaleString () array to string

Definition: Returns a string representing an array element. The string consists of the toLocaleString() return values for each element in the array joined (separated by commas) by calling the join() method.

Grammar:

array.toLocaleString()
Copy the code

Parameter: None.

let a=[{name:'OBKoro1'},23,'abcd',new Date()]; let str=a.toLocaleString(); // [object Object],23, abCD,2018/5/28 PM 1:52:20Copy the code

Each element in the array calls its own toLocaleString method. An object calls the object’s toLocaleString. A Date calls Date’s toLocaleString.

ToString () array toString

Definition: The toString() method converts an array to a comma-linked string.

array.toString()
Copy the code

Parameter: None.

The effect of this method is the same as that of the JOIN method, which is used to convert arrays to strings. However, compared with the Join method, this method has no advantages and cannot customize string delimiters. Therefore, it is not recommended to use this method.

Note that js calls this method to automatically convert arrays to strings when operating on arrays and strings

Let b= ['toString',' demo '].toString(); // toString, demo let a= [' call toString',' connect after me ']+' la la la la '; // Call toString, link after me la la laCopy the code

Slice () shallowly copies array elements

Definition: Method returns a shallow copy of a portion of the selected array from the beginning to the end (excluding the end) into a new array object without modifying the original array.

Note: Strings also have a slice() method that extracts strings, so don’t get confused.

Grammar:

array.slice(begin, end);
Copy the code

Parameters:

Begin (Optional): Indicates the index value. It accepts negative values. The value is 0 by default.

End (Optional): index value (excluding), accepts a negative value, and ends at the end of the index. The default value is the end of the array (including the last element).

let a= ['hello','world']; Let b = a.s lice (0, 1); // ['hello'] a[0]=' change array '; console.log(a,b); // [' change array ','world'] ['hello'] b[0]=' change array '; console.log(a,b); // [' change array ','world'] [' change array copied ']Copy the code

As above, the new array is shallow-copied, the elements are simple data types, and changes do not interfere with each other.

If it’s a complex data type (object, array), changing one of them will change the other.

let a= [{name:'OBKoro1'}]; let b=a.slice(); console.log(b,a); / / / {" name ":" OBKoro1}] [{" name ":" OBKoro1} "] / / a [0]. Name = 'to change the original array; // console.log(b,a); / / / {" name ":" to change the original array "}] [{" name ":" to change the original array "}] [0]. / / b name = 'change copy an array, b [0]. Belonged to =' change copy array; / / / {" name ":" change copy an array ", "belonged to" : "change copy an array"}] [{" name ":" change copy an array ", "belonged to" : "change copy an array"}]Copy the code

The reason is explained above: slice() is a shallow copy. For complex data types, a shallow copy copies only Pointers to the original array, so changing either the original array or the shallow-copied array changes the original array’s data.

Concat () Array concatenation

Definition: Method used to merge two or more arrays, returning a new array.

Grammar:

var newArr =oldArray.concat(arrayX,arrayX,...... ,arrayX)Copy the code

Parameters:

ArrayX (required) : This parameter can be a concrete value or an array object. It can be as many as you want. eg1:

let a = [1, 2, 3]; let b = [4, 5, 6]; // join two arrays let newVal=a.concat(b); // [1,2,3,4,5,6] // join three arrays let c = [7, 8, 9] let newVal2 = a.c (b, c); / /,2,3,4,5,6,7,8,9 [1] / add elements let newVal3 = a.c oncat (' add elements', b, c, 'and a'); / / [1, 2, 3, 4 "add elements,",5,6,7,8,9, "plus a"] / / merge nested arrays will shallow copy nested let d = [1, 2]; let f = [3,[4]]; let newVal4 = d.concat(f); / / [1, 2, 3, [4]]Copy the code

ES6 extension operators… Merge arrays:

Because ES6 syntax is more concise, so now MERGE arrays I mostly use… To deal with… The operator can implement each chestnut of cancat with greater conciseness and a high degree of customization of array element positions.

let a = [2, 3, 4, 5] let b = [ 4,...a, 4, 4] console.log(a,b); // [2, 3,4,5] [4,2,3,4,5,4,Copy the code

For more details on extenders, follow Ruan’s introduction to ECMAScript 6

IndexOf () finds the specified element subscript

Definition: Returns the first index in the array where a given element can be found, or -1 if none exists.

Grammar:

array.indexOf(searchElement,fromIndex)
Copy the code

Parameters: searchElement(required): the element to be searched fromIndex(optional): the location to start the search (cannot be greater than or equal to the length of the array, returns -1), accepts negative values, defaults to 0. Strict equality search: Unlike string indexOf, array indexOf searches for elements using strict equality ===, that is, array elements must match exactly to be searched. Note: indexOf() does not recognize NaN

eg:

Let a = [' la-la-la, 2,4,24, NaN]. The console log (Anderson ndexOf (', ')); // -1 console.log(a.indexOf('NaN')); // -1 console.log(a.indexof (' la la ')); //Copy the code

Usage Scenarios:

Array dereference Performs operations based on the obtained array subscript, changing the value in the array, etc. Check whether it exists and perform the operation.

LastIndexOf () finds the specified element subscript

Definition: Method returns the index of the last element in an array, or -1 if none exists. (Look up from the back of the array)

Grammar:

arr.lastIndexOf(searchElement,fromIndex)
Copy the code

Parameters: searchElement(required): the element to be searched fromIndex(Optional): Reverse lookup starting position, default array length -1, that is, find the entire array. There are three rules about fromIndex:

1. Positive. If the value is greater than or equal to the length of the array, the entire array is searched.

2. Negative values. Think of it as an offset forward from the end of the array. (For example, -2, starting from the last second element of the array.)

3. Negative. If the absolute value is greater than the array length, the method returns -1, that is, the array will not be looked up.

Let a = [' OB ', 4, 'Koro1', 1, 2, 'Koro1, three, four, five,' Koro1]; // let b= a.listIndexof ('Koro1',4); // let b= a.listIndexof ('Koro1',4); // let b= a.listIndexof ('Koro1',100); // let b= a.listIndexof ('Koro1',100); // let b= a.lastIndexof ('Koro1',-11); Let b= a.listIndexof ('Koro1',-9); let b= a.listIndexof ('Koro1',-9); // Look forward to the second element, 4. If no element is found, return -1Copy the code

ES7 includes() finds if the array contains an element

Definition: Returns a Boolean value indicating whether an array contains a given value

Grammar:

array.includes(searchElement,fromIndex=0)
Copy the code

Parameters: searchElement(required): the element being searched fromIndex(optional): The default value is 0. The parameter indicates the start of the search and accepts negative values. If the value exceeds the array length, the array will not be searched, return false. Negative absolute value exceeds long array degree, reset to search from 0. The includes method was developed to remedy the shortcomings of the indexOf method:

The indexOf method does not recognize NaN values. The indexOf method does not contain a value that is not equal to -1

eg:

let a=['OB','Koro1',1,NaN]; // let b=a.includes(NaN); // let b=a.includes('Koro1',100); // let b=a.includes('Koro1',-3); // let b=a.includes('Koro1',-3); // let b=a.includes('Koro1',-100); // let b=a.includes('Koro1',-100); // true Searches the entire array if the absolute value exceeds the length of the arrayCopy the code

Compatibility (MDN): chrome47, Firefox 43,Edge 14,Opera 34, Safari 9,IE not implemented.

Through the array

There are 12 methods that iterate over an array without changing the original array:

ES5: forEach, every, some, filter, map, reduce, reduceRight, ES6: find, findIndex, keys, values, and entriesCopy the code

Try not to change the length of the array (delete/add) while traversing

forEach

Definition: Executes a callback function for each item in the array that has valid values, in ascending order.

Grammar:

array.forEach(function(currentValue, index, arr), thisValue)
Copy the code

Parameters:

Function (required): The function to be called for each element in the array.

CurrentValue (required), the value of the current element of the array 2. index(optional), the index of the current element 3. arr(optional), the array objectCopy the code

ThisValue (Optional): The value of this binding object when the callback function is executed, default is undefined

You should know about forEach() :

  • There is no way to exit the loop. You can only exit this callback with return for the next callback.
  • It always returns undefined, even if you return a value.

The following similar syntax also applies to these rules

1. The callback function is not executed for an empty array. 2. The callback function is skipped for an element that has been deleted during iteration, or for an empty element. The number of iterations is determined before the first loop, and elements added to the array will not be iterated. 4. If an existing value is changed, the value passed to the callback is traversed up to their momentCopy the code

eg

let a = [1, 2, ,3]; Let obj = {name: 'OBKoro1'}; let obj = {name: 'OBKoro1'}; Let result = a.float (function (value, index, array) {a[3] = 'change element '; A.ush (' added to end, not traversed ') console.log(value, 'first argument passed by forEach '); // Print 1,2, respectively, and change the element console.log(this.name); // OBKoro1 prints this three times on the obj object // break; // return value; Console. log(' not executed because return will execute the next loopback ')}, obj); console.log(result); // Return undefined even if a value is returnedCopy the code

Every checks whether all elements of the array match the criteria

This method checks whether all elements of an array conform to the conditional syntax defined by the function:

array.every(function(currentValue, index, arr), thisValue)
Copy the code

Parameters :(these methods have similar syntax for parameters)

Function (required): The function to be called for each element in the array.

CurrentValue (required), the value of the current element of the array 2. index(optional), the index of the current element 3. arr(optional), the array object itselfCopy the code

ThisValue (Optional): The value of this binding object when the callback function is executed. The default value is undefined.

If one element in the array is detected to be unsatisfied, the entire expression returns false and the remaining elements are not tested. Returns true if all elements satisfy the condition. =

eg:

function isBigEnough(element, index, array) { return element >= 10; } let result = [12, 5, 8, 130, 44]. Every (isBigEnough); // false let result = [12, 54, 18, 130, 44].every(isBigEnough); [12, 5, 8, 130, 44]. Every (x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // trueCopy the code

Is there any element in the some array that meets the criteria

Definition: Whether there are elements in the array that meet the criteria

Grammar:

array.some(function(currentValue, index, arr), thisValue)
Copy the code

Parameters :(these methods have similar syntax for parameters)

Function (required): The function to be called for each element in the array.

CurrentValue (required), the value of the current element of the array 2. index(optional), the index of the current element 3. arr(optional), the array object itselfCopy the code

ThisValue (Optional): The value of this binding object when the callback function is executed, default is undefined

Method return value rule:

If one element meets the criteria, the expression returns true, and the remaining elements are not tested.

If no element satisfies the condition, false is returned.

function isBigEnough(element, index, array) { return (element >= 10); } let result = [2, 5, 8, 1, 4]. Some (isBigEnough); // false let result = [12, 5, 8, 1, 4].some(isBigEnough); // trueCopy the code

Filter Filters the original array and returns the new array

Definition: Returns a new array containing all the elements of the tests implemented by the provided function.

Grammar:

let new_array = arr.filter(function(currentValue, index, arr), thisArg)
Copy the code

Parameters :(these methods have similar syntax for parameters)

Function (required): The function to be called for each element in the array.

CurrentValue (required), the value of the current element of the array 2. index(optional), the index of the current element 3. arr(optional), the array objectCopy the code

ThisValue (Optional): The value of this binding object when the callback function is executed, default is undefined

eg:

let a = [32, 33, 16, 40]; let result = a.filter(function (value, index, array) { return value >= 18; // return all elements in array A greater than 18}); console.log(result,a); / / [32,33,40] [32,33,16,40]Copy the code

Map processes each element in the array, returning a new array

Definition: Creates a new array, the result of which is returned when each element in the array calls a provided function.

Grammar:

let new_array = arr.map(function(currentValue, index, arr), thisArg)
Copy the code

Parameters :(these methods have similar syntax for parameters)

Function (required): The function to be called for each element in the array.

CurrentValue (required), the value of the current element of the array 2. index(optional), the index of the current element 3. arr(optional), the array objectCopy the code

ThisValue (Optional): The value of this binding object when the callback function is executed, default is undefined

eg:

let a = ['1','2','3','4']; Let result = a.maap (function (value, index, array) {return value + 'a.maap'}); console.log(result, a); / / / "1 new array elements", "2 new array elements", "3 new array elements", "four new array element"] [" 1 ", "2", "3", "4"]Copy the code

Reduce provides an accumulator for arrays that merge into a single value

Definition: The reduce() method applies a function (from left to right) to each element in the accumulator and array, eventually merging into a single value.

Grammar:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy the code

Parameters:

Function (required): The function to be called for each element in the array.

CurrentValue (required), the value of the current element of the array 3. index(optional), the index of the current element 4. arr(optional), the array object itselfCopy the code

InitialValue (Optional): Specifies the first parameter of the first callback. When the callback is first executed:

If initialValue is provided when reducing is called, the first total will be equal to initialValue, where currentValue is equal to the first value in the array;

If initialValue is not provided, total is equal to the first value in the array, and currentValue is equal to the second value in the array. If the array is empty at this point, TypeError is raised.

If the array has only one element and initialValue is not provided, or initialValue is provided but the array is empty, the callback will not be executed and the unique value of the array will be returned.

eg:

// Let sum = [0, 1, 2, 3]. Reduce (function (a, b) {return a + b; }, 0); / / 6 / / convert two-dimensional arrays into one dimensional array elements on the let flattened = [[0, 1], [2, 3], [4, 5]], the reduce ((a, b) = > a.c oncat (b), []); // [0, 1, 2, 3, 4, 5]Copy the code

reducerRight

This method is the same as the reduce method except that it runs in the opposite direction. For details, see the reduce method.

ES6 find(),findIndex() finds array elements based on criteria

Find () definition: finds the first qualified array member and returns that member, or undefined if none exists.

FindIndex () returns the position of the first qualified array member, or -1 if all members fail.

These two methods

Grammar:

let new_array = arr.find(function(currentValue, index, arr), thisArg)
let new_array = arr.findIndex(function(currentValue, index, arr), thisArg)
Copy the code

Parameters :(these methods have similar syntax for parameters)

Function (required): The function to be called for each element in the array.

CurrentValue (required), the value of the current element of the array 2. index(optional), the index of the current element 3. arr(optional), the array object itselfCopy the code

ThisValue (Optional): The value of this binding object when the callback function is executed, default is undefined

Both methods can recognize nans and complement indexOf.

eg:

// find let a = [1, 4, -5, 10].find((n) => n < 0); / / return elements - 5 b = [1, 4, 5, 10, NaN]. Find ((n) = > Object. The is (NaN, n)); Let a = [1, 4, -5, 10]. FindIndex ((n) => n < 0); / / return index 2 let b = [1, 4, 5, 10, NaN]. FindIndex ((n) = > Object. The is (NaN, n)); // return index 4Copy the code

Browser Compatibility (MDN):Chrome 45,Firefox 25,Opera 32, Safari 8, Edge Yes,

ES6 keys()&values()& Entries () Traverses key names, traverses key values, traverses key names + key values

Definition: Each of the three methods returns a new Array Iterator that contains different values depending on the method.

Grammar:

array.keys()
array.values()
array.entries()
Copy the code

Parameter: None.

Traversal chestnut (from ECMAScript 6 Introduction) :

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"
Copy the code

In the for… If you want to exit in the middle of the loop, you can use break to exit the loop.

If you don’t use for… The of loop can be iterated manually by calling the next method of the iterator object:

let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c
Copy the code

Entries () MDN :Chrome 38, Firefox 28,Opera 25,Safari 7.1

MDN :Chrome 38, Firefox 28,Opera 25,Safari 8,

Note: It is currently only supported by Safari 9, not implemented in other browsers, and the Babel transcoder is not yet implemented

String method

indexOf(substr, [start])

The indexOf method searches for and (if found) returns the indexOf the character or substring found in the string. If none is found, -1 is returned. Start is an optional argument that specifies where in the string to Start the search. The default value is 0.

//indexOf(char/substring) var sentence="Hi, my name is Sam!" if (sentence.indexOf("Sam")! =-1) alert("Sam is in there!" )Copy the code

lastIndexOf(substr, [start])

The lastIndexOf() method returns the index of the last occurrence of the specified text in the string, or -1 if it is not found. “Start” is an optional argument that specifies where in the string to Start the search. The default value is String.length-1.

//lastIndexOf(substr, [start])
var myString = 'javascript rox';
console.log(myString.lastIndexOf('r'));
//output: 11
Copy the code

charAt(x)

CharAt (x) returns the character at position X in the string, with subscripts starting at 0.

//charAt(x) var myString = 'jQuery FTW!!! '; console.log(myString.charAt(7)); //output: FCopy the code

charCodeAt(x)

CharCodeAt (x) returns the Unicode value of the character at position X in the string.

//charCodeAt(position)
var message="jquery4u"
//alert "113"
alert(message.charCodeAt(1)
Copy the code

concat(v1,v2..)

The concat() method is used to concatenate two or more strings. This method does not alter the existing string, but returns a new concatenated string.

//concat(v1, v2,..)
var message="Sam"
var final=message.concat(" is a"," hopeless romantic.")
//alerts "Sam is a hopeless romantic."
alert(final)
Copy the code

match(regexp)

Searches for matches in a string based on a regular expression. If no match is found, an array of information or NULL is returned.

//match(regexp) //select integers only
var intRegex = /[0-9 -()+]+$/;  
 
var myNumber = '999';
var myInt = myNumber.match(intRegex);
console.log(isInt);
//output: 999
 
var myString = '999 JS Coders';
var myInt = myString.match(intRegex);
console.log(isInt);
//output: null
Copy the code

replace(regexp/substr, replacetext)

The replace() method is used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression.

//replace(substr, replacetext)
var myString = '999 JavaScript Coders';
console.log(myString.replace(/JavaScript/i, "jQuery"));
//output: 999 jQuery Coders
 
//replace(regexp, replacetext)
var myString = '999 JavaScript Coders';
console.log(myString.replace(new RegExp( "999", "gi" ), "The"));
//output: The JavaScript Coders
Copy the code

slice(start, [end])

The slice() method extracts a portion of a string and returns a new string. Includes all characters from the beginning of the string (including start) to the end of the string (excluding end).

//slice(start, end) var text="excellent" text. Slice (0,4) //returns "exce" text. Slice (2,4) //returns "ce"Copy the code

split(delimiter, [limit])

The split() method splits a string into an array of strings, returning an array of strings that does not include delimiter itself. The optional “limit” is an integer that allows you to specify the maximum number of array elements to return

substr(start, [length])

The substr() method extracts a specified number of characters from the start subscript in the string. Returns a new string containing the length of characters starting at start (including the character referred to by start). If length is not specified, the string returned contains characters from start to the end of the string.

//substr(from, to) var text="excellent" text. Substr (0,4) //returns "exce" text. Substr (2,4) //returns "cell"Copy the code

substring(from, [to])

The substring() method is used to extract the string intermediate between two specified subscripts. The substring returned by square includes characters at start but not at stop, and optional to. If omitted, the substring is returned up to the end of the string.

//substring(from, [to]) var myString = 'javascript rox'; MyString = myString. Substring (0, 10); console.log(myString) //output: javascriptCopy the code

toLowerCase()

The toLowerCase() method is used to convert a string toLowerCase.

//toLowerCase()
var myString = 'JAVASCRIPT ROX';
myString = myString.toLowerCase();
console.log(myString)
//output: javascript rox
Copy the code

toUpperCase()

The toUpperCase() method is used to convert a string toUpperCase.

//toUpperCase()
var myString = 'javascript rox';
myString = myString.toUpperCase();
console.log(myString)
//output: JAVASCRIPT ROX
Copy the code

includes()

The includes() method checks whether a string contains the specified string or character.

//includes()
var mystring = "Hello, welcome to edureka";
var n = mystring.includes("edureka");
//output: True
Copy the code

repeat()

Repeat () constructs and returns a new string that contains copies of a specified number of strings to be concatenated together.

//repeat()
var string = "Welcome to Edureka";
string.repeat(2);
//output: Welcome to Edureka Welcome to Edureka
Copy the code

valueOf()

The valueOf () method returns a String object’s original value (primitive value), the value is equal to the String. The prototype. The toString ().

//valueOf() var mystr = "Hello World!" ; var res = mystr.valueOf(); //output: Hello World!Copy the code

trim()

The trim() method removes whitespace characters from both ends of a string. Whitespace characters in this context are all whitespace characters (space, TAB, no-break space, etc.) and all line terminator characters (such as LF, CR)

//trim()
var str = "     Hello Edureka!     ";
alert(str.trim());
Copy the code

Object methods

,

Create an object

  • Literal creation
  • The built-in Object Object is created
  • Constructor creation
  • Factory Pattern creation
  • Prototype pattern creation
  • Composite pattern creation
  • Parasitic composite model creation

Object.is()

Object.is(value1, value2) is used to determine whether two values are equal

Is NaN equal to itself

Object.is(NaN,NaN) // true
console.log(NaN === NaN) //false
Copy the code

Is plus 0 equal to minus 0

Objcet.is(+0, -0) // false
console.log(+0 === -0) // true
Copy the code

Object.assign()

Object.assign(target, … Sources is used to copy the values of all enumerable properties from one or more source objects to the target object, which will be returned.

Parameters:

Target: indicates the target object.

Sources: source object; Return value: target object.

(1) Used to copy a new object, does not affect the original object

let obj = { a: 1 };
let copy = Object.assign({}, obj);
console.log(copy);    // { a: 1 }
Copy the code

(2) Used to merge object attributes, copy all enumerable attributes of the source object to the target object.

//object.assign(obj, obj2) obj2 is the source object, obj is the target object, let obj = {a: 1}; let obj2={b:2}; console.log(Object.assign(obj,obj2)===obj); //true, returns the target object console.log(obj); //{a:1,b:2} obj has been changedCopy the code

(3) If the target object and the source object have the same key, the attribute will be overwritten by the source object’s attribute, and the subsequent source attribute will overwrite the previous source attribute of the same key.

let obj = { a: 1 };
let obj2 = {a:5,b:2};
let obj3 = {b:1,d:0};
Object.assign(obj,obj2,obj3);

console.log(obj);       // {a: 5, b: 1, d: 0}
Copy the code

(4) If there is only one assign object, the assign object will be returned without operation.

let obj = { a: 1 }
Object.assign(obj);
console.log(obj);        //{a:1}
Copy the code

(5)Object.assign() implements shallow copy instead of deep copy. That is, if the value of an attribute of the source object is an object, the target object copies a reference to that object.

let obj1 = { a: 0 , b: { c: 0}};
let obj2 = Object.assign({}, obj1);
obj1.b.c=5;

console.log(obj2)       //{a:0,b:{c:5}};
Copy the code

(6) Add new attributes to the current object

const a = {};
Object.assign(a, { x: 3 });  // a => x:3
Copy the code

Object.hasOwnProperty()

The hasOwnProperty() method returns a Boolean value indicating whether the object has the specified property as its own (non-inherited) property. obj.hasOwnProperty(prop)

parameter

Prop: The name of the property string or Symbol to be tested.

Return value: A Boolean used to determine whether an object contains the specified attribute.

All objects that inherit from Object inherit to the hasOwnProperty method. This method can be used to detect whether an object has a specific property of itself; Unlike the IN operator, this method ignores attributes inherited from the stereotype chain.

let obj=new Object(); obj.a=5; Console. log(obj.hasownProperty ('a ')) // true delete obj.a; The console. The log (obj. HasOwnProperty (' a ')). / / falseCopy the code

Object.defineProperty()

Object.defineproperty () is used to do some operations on attributes of an Object.

Syntax: Object.defineProperty(obj, prop, Descriptor)

Parameter Description:

Obj: Absolutely. Target object prop: Required. Attribute name descriptor to be defined or modified: required. Properties owned by the target propertyCopy the code

For the object to the property, we can set some properties for the property. Can the value of the property be overridden? Is it read-only? ; Can be for.. In or object.keys () traversal, can I delete the target property or can I modify the property again?

Just a couple of examples

  1. Value: The value of the property, which can be of any type. The default value is undefined
Object.defineproperty (obj,"newKey",{}); console.log( obj.newKey ); / / undefined -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / the second case: set the value attribute Object. DefineProperty (obj, newKey, {value: "hello"}); console.log( obj.newKey ); //helloCopy the code
  1. Writable: Whether the value of a property can be overridden (default: false). Set to true can be overridden; Set to false and cannot be overridden.
Let obj = {} // if writable is set to false, it cannot be overridden. Object.defineProperty(obj,"newKey",{ value:"hello", writable:false }); Obj. NewKey = "change value"; console.log( obj.newKey ); / / hello -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / the second case: DefineProperty (obj,"newKey",{value:"hello", writable:true}); Obj. NewKey = "change value"; console.log( obj.newKey ); //change valueCopy the code
  1. Enumerable: Whether this property can be enumerable (use for… In or object.keys ()). Set to true to enumerate; Set to false and cannot be enumerated. (Default: false).
Var obj = {} // Enumerable is set to false and cannot be enumerable. Object.defineProperty(obj,"newKey",{ value:"hello", writable:false, enumerable:false }); For (var attr in obj){console.log(attr); } // Enumerable is true and can be enumerable. Object.defineProperty(obj,"newKey",{ value:"hello", writable:false, enumerable:true }); For (var attr in obj){console.log(attr); //newKey }Copy the code

4. Any additional information, writable, signals, enumerable, can be deleted without any additional control system. Set to true to remove or reset features; If set to false, the feature cannot be deleted or reset. The default is false. This property does two things:

Whether the target attribute can be deleted Using delete Whether the target attribute can be set again

/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - test whether a target attribute can be delete -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the var obj = {} / / the first kind of circumstance: configurable set to false, cannot be deleted. Object.defineProperty(obj,"newKey",{ value:"hello", writable:false, enumerable:false, configurable:false }); // Delete obj. NewKey; console.log( obj.newKey ); // The second case: the 64x is set to true and can be deleted. Object.defineProperty(obj,"newKey",{ value:"hello", writable:false, enumerable:false, configurable:true }); // Delete obj. NewKey; console.log( obj.newKey ); / / undefined / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- test whether can modify attributes/characteristics again -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- var obj = {} / / in the first case: If the 64x is set to false, the properties and features cannot be modified again. Object.defineProperty(obj,"newKey",{ value:"hello", writable:false, enumerable:false, configurable:false }); DefineProperty (obj,"newKey",{value:"hello", writable:true, Enumerable :true, different :true}); console.log( obj.newKey ); // If the new device is set to true, the property/feature can be modified again. Object.defineProperty(obj,"newKey",{ value:"hello", writable:false, enumerable:false, configurable:true }); DefineProperty (obj,"newKey",{value:"hello", writable:true, Enumerable :true, different :true}); console.log( obj.newKey ); //helloCopy the code

In addition to newly defined properties, you can set properties/attributes for existing properties.

// Attributes added when defining objects are deletable, rewritable, and enumerable. Var obj = {test:"hello"} console.log( obj.test ); //'change value' object.defineProperty (obj,"test",{writable:false}) // Rewrite value obj. Test = 'change value again'; console.log( obj.test ); // still: 'change value'Copy the code

DefineProperty allows you to add any property to the Object, and the default values of Enumerable and writable are false if the property is not specified

var obj = {}; // The new property, named 64x, enumerable, works without any additional control. // Object.defineProperty(obj,'newKey',{}); // set the value obj.newKey = 'hello'; console.log(obj.newKey); //undefined // enumeration for(var attr in obj){console.log(attr); //undefined // enumeration for(var attr in obj){console.log(attr); }Copy the code

Object.keys()

The object.keys () method returns an array of the given Object’s own enumerable properties, the order of the array’s properties and the use of for.. The main difference between the two is that a for-in loop also enumerates the properties on its prototype chain

Object.keys(obj)

parameter

Obj: To return the object whose enumeration is its own property.

Return value: an array of strings representing all the enumerable properties of a given object.

1) Array Array object (return index value)

Let arr = [1, 2, 3]; Keys (arr) // ["0", "1", "2 "]Copy the code

(2) Object (return key)

let obj = { foo: "bar", baz: 42 }; Object. The keys (obj) / / / "foo", "baz"Copy the code

(3) Class array, object

Let obj = {0: "a", 1: "b", 2: "c "}; Object.keys(obj) // ["0", "1", "2"]Copy the code

(4) Random key sorting of class array objects

Let Obj = {100: 'a ', 2: 'b ',7: 'c '}; console.log(Object.keys(Obj)); // ['2', '7', '100 ']. Returns the result sorted from smallest to largestCopy the code

Object.values()

The object.value () method returns an array of all the enumerable property values of a given Object, in the same order as using for.. The in loop is the same, returning the value of the Object, as opposed to object.key ()

Example: (1) Normal objects

let obj={a:1,b:2,c:3};
console.log(Object.values(obj))         //  [1, 2, 3]
Copy the code

(2) Class array object

let obj ={0:'a',1:'b',2:'c'};
console.log(Object.values(obj)).       //  a,b,c
Copy the code

(3) The key value is an unordered number

let obj={100:'a',10:'b',1:'1'};
console.log(Object.values(obj)).   // ["1", "b", "a"]
Copy the code

Object.entries()

Object.entries() returns an array of elements corresponding to key and value pairs of enumerable properties found directly on Object. The order of properties is the same as that given by manually looping through the object’s property values.

Example: (1) If the key value is a normal character, the return key value is a string

let obj1 = {a:1,b:2};
let obj2 = Object.entries(obj1);
console.log(obj2) ;       //  [ ["a":1],["b":2] ] 
Copy the code

(2) If the key value is a number, the returned key value is also a string

let obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj));     // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] 
Copy the code

(3) When the number of the key value is out of order, it will return it sorted

let anObj = { 100: 'a', 2: 'b', 9: 'c' };
console.log(Object.entries(anObj));   //[["2","b"],["9","c"],["100","a"]]
Copy the code

(4) Expand the object

const object1 = {
 a: 'somestring',
 b: 42
};

for (let [key, value] of Object.entries(object1)) {
 console.log(`${key}: ${value}`);
}
//     "a: somestring"
//     "b: 42"
Copy the code

Refer to the article

Study notes – Object method collation

Js array detailed operation methods and parsing collection

JS top 20 common string methods and their usage

Quick mastery of JavaScript string methods