JS built-in objects

Time:2024-2-14

JS built-in objects

preamble

In today’s digital age, front-end technologies are increasingly becoming key to shaping the user experience. We need to use some properties of many js built-in objects in our development to help us develop faster. Maybe you are a newbie to the front-end field or a developer who wants to know more about built-in objects, no matter what your experience is, this blog will give you a detailed explanation of built-in objects of js.


Author Bio:Programmer Xiaohao, a full-stack engineer with a passion for programming, worked for theAzure, TencentHe is currently working in a large Internet company, technology stack: Vue, React, Python, Java.
This article is featured in Little Howe’sforward part of sth.A series of columns, with updates to followGetting Started with Front-End and Front-End InterviewsSome of the related articles, hand in hand to take you from zero learning front-end to interview to find a job, and if there are students who want to enter the front-end field of work, thisforward part of sth.The column will help you, welcome to follow it!
I will continue to followAIGC and the field of artificial intelligenceSome of the movements and summarized in the blog, everyone interested can follow myartificial intelligence (AI)columns
🌊 cloud nativeThe introductory learning series for anyone interested in the

Table of Contents for this article

global object

value property

Infinity

Global PropertiesInfinity is a numerical value that represents infinity.

Infinity Attribute Characterization of Properties

Attributesboolean
writablefalse
enumerablefalse
configurablefalse

clarification

  • Infinity is a property of the global object, i.e. it is a global variable.
  • Infinity The initial value ofNumber.POSITIVE_INFINITY。

Infinity greater than any value. This value is much like infinity in the mathematical sense, such as any positive value multiplied byInfinity because ofInfinity , any value (exceptInfinityrespond in singing-Infinity ) divided byInfinity is 0.

typical example

🌰 code example:

console.log(Infinity);
// Infinity
console.log(Infinity + 1);
// Infinity
console.log(Math.pow(10, 1000));
// Infinity
console.log(Math.log(0));
// Infinity
console.log(1 / Infinity);
// 0

NaN

Global PropertiesNaN The value of indicates that it is not a number (Not-A-Number).

Attributesboolean
writablefalse
enumerablefalse
configurablefalse

clarification

  • NaN is a property of a global object.
  • NaN The initial value of the attribute is theNaNpeaceNumber.NaN The value of the same.
  • It is rare for coding to make direct use of theNaN. This is usually done when the calculation fails asMath that appears as the return value of one of the methods of (for example:Math.sqrt(-1)) or when trying to parse a string into a number and failing (for example:parseInt('blabla'))。

come (or go) backNaN Summary of the situation:

  • infinity divided by infinity (math.)
  • Do open operations on any negative number
  • Arithmetic operators are used with operands that are not numbers or cannot be converted to numbers
  • String parsed as number

typical example

value checking

The equal sign operator may not be used to determine whether a value isNaN. It is necessary to useNumber.isNaN() maybeisNaN()function to make a judgment.

In performing a self-comparison, theNaN is the only value that is not fully equivalent to itself.

NaN === NaN;
//	false


Number.NaN === NaN;
// false


isNaN(NaN);
// true;


isNaN(Number.NaN);
// true;
function valueIsNaN(v) {
  return v !== v;
}
valueIsNaN(1);
// false
valueIsNaN(NaN);
// true
valueIsNaN(Number.NaN);
// true

utilizationisNaN() You can avoid implicit type conversion problems by checking if the value is a number before you use it.

function detectIsNaN(value) {
  return typeof value === 'number' && isNaN(value);
}

undefined

undefined attribute is a special value. If a variable has been declared but not yet initialized, the value of theundefined。

The attribute isGlobal A read-only property (a constant, to be precise) of an object. This property is supported by all major browsers.

clarification

If a variable is not initialized with an assignment, the value of theundefined. If a function has no return value, its return value defaults toundefined。

function property

eval

eval() function is used to compute and execute JavaScript code expressed as a string.eval() function enables JavaScript to dynamically execute JavaScript source code.

eval() The function belongs to theGlobal object, which is supported by all major browsers.

grammatical

eval(code);
parameterstypologyclarification
codeString typologyString containing valid JavaScript code

⚠️ attention (heed): ParameterscodeMust be a raw string, not in the form of a String object. If the parametercode is not the original string, theneval() The function does not execute the code and returns it unchanged.

If the parametercode If the JavaScript code in the file is not legal, an exception will be thrown.

eval() The return value of a function is of any type, and its return value is determined by the parametercode The specific JavaScript code in the

clarification

  • pass on toeval() The context in which the function’s code is executed and the context in which the call to theeval() function when the context is the same (i.e., the scope is unchanged).
  • Please confirm yourselfcode The source of the code is trusted, otherwise useeval() The function has certain safety hazards.

typical example

let x = 2,
  y = 39,
  z = '42';


eval('x + y + 1');
// 42


eval(z);
// 42

isNaN

isNaN() function is used to determine if the specified number is a non-numeric valueNaN。

This function belongs to theGlobalobject, which is supported by all major browsers.

grammatical

isNaN(number);
parameterstypologyclarification
numberNumber typologySpecified value

⚠️ attention (heed): If the parameternumber is not of type Number, thenisNaN() The function will force the value to be converted to Number before making a judgment. Most values of other types cannot be forced to Number, so the result isNaNnamelyisNaN() function returnstrue。

  • isNaN()
    

    The return value of the function is of type Boolean.

    • If the specified number isNaNIf you are a member of the group, you will be able to returntrue
    • If the specified number is notNaN then it returnsfalse。

clarification

  • This function is usually used to detect the data from theparseInt() respond in singingparseFloat() The return value of the function.
  • Converting certain non-numeric values that cannot be forced to be converted to numeric values also results in theNaN。
  • NaN cannot be determined by the equality operator because theNaN is the only value that is not equal to itself.

typical example

isNaN(NaN);
// true
isNaN(undefined);
// true
isNaN({});
// true


isNaN(true);
// false
isNaN(null);
// false
isNaN(37);
// false


// strings
isNaN('37');
// false: can be converted to a value 37
isNaN('37.37');
// false: can be converted to a value 37.37
isNaN('');
// false: empty string is converted to 0
isNaN(' ');
// false: strings containing spaces are converted to 0


// dates
isNaN(new Date());
// false
isNaN(new Date().toString());
// true


isNaN('blabla');
// true: "blabla" cannot be converted to a numeric value.

parseFloat

parseFloat()function forConverts a string to a floating-point number and back.。

This function belongs to theGlobal object, which is supported by all major browsers.

grammatical

parseFloat(numberString);
parameterstypologyclarification
numberStringString typologyA string that needs to be converted to a floating point number.
  • Returns the converted floating-point number.

    number
    

    Type.

    • If the specified string contains non-numeric characters, as long as the beginning portion of the string conforms to the floating-point rule, theparseFloat() The function converts this part of the string to a number (from the beginning of the string until a non-numeric character is encountered).
    • If the string begins with a non-numeric character, then return theNaN。

typical example

  • Return to normal numbers
parseFloat('3.14');
parseFloat('314e-2');
parseFloat('0.0314E+2');
parseFloat('3.14more non-digit characters');


// all return 3.14
  • come (or go) backNaN
parseFloat('MDN');
// NaN
parseFloat(null);
// NaN
parseFloat([]);
// NaN
parseFloat({});
// NaN

parseInt

parseInt() function forConverts a string to an integer and back. This function treats the string as a representation of the specified decimal form.

This function belongs to theGlobal object, which is supported by all major browsers.

grammatical

parseInt( numString [, radix ] )
parameterstypologyclarification
numStringString typologyStrings that need to be converted to integers
radixNumber typologyOptionally, the specified base number (between[2, 36] between the values.)

For example, the parameterradix is 2, then thenumString treated as binary; the parameterradix is 8, it is treated as octal; the parameterradix is 16, it is treated as hexadecimal.

If not providedradix parameter, then theparseInt() The function will be based on the parameternumString prefix to determine the base of the conversion. If thenumString The prefix of0x, then it is converted to hexadecimal; if the prefix is0, is converted to octal; in all other cases, it is converted to decimal.

  • parseInt()The return value of the function is of type Number.Returns the converted integer
    • If the specified string contains non-numeric characters, as long as the beginning part of the string matches the conversion rules for integers, then theparseInt() The function converts this part of the string to an integer (from the beginning of the string until a non-numeric character is encountered).
    • If the string begins with a non-numeric character, then return theNaN。

typical example

  • normal useparseInt()The following are returned 15
// Binary
parseInt('1111', 2);


// Octal
parseInt('17', 8);
parseInt(021, 8);


// Decimal
parseInt('015', 10);
parseInt(15.99, 10);
parseInt('15,123', 10);
parseInt('15 * 3', 10);
parseInt('15e2', 10);
parseInt('15px', 10);


parseInt('12', 13);


// Hexadecimal
parseInt('0xF', 16);
parseInt('F', 16);
parseInt('FXX123', 16);
  • The following are returnedNaN
parseInt('Hello', 8);
// not a number


parseInt('546', 2);
// except 0 & 1,other number are not valid binary numbers

decodeURI

decodeURI() function is used to decode an encoded Uniform Resource Identifier (URI) and return its non-encoded form.

This function belongs to theGlobal object, which is supported by all major browsers.

grammatical

decodeURI(encodedURIString);
parameterstypologyclarification
encodedURIStringString typologyEncoded URI string

decodeURI() The return value of the function isstring type, which returns a decoded URI.

Escape all recognizable sequences in the encoded URI into theConvert to Original Charactersbut cannot decode those that would not beencodeURI Encoded content (e.g.#)。

typical example

let a = 'Hello JavaScript!';
let b = encodeURI(a);


console.log(b);
// return '%E4%BD%A0%E5%A5%BDJavascript!'


let c = decodeURI(b);
// return 'Hello Javascript! '

encodeURI

encodeURI() function converts a URI string into a string in escape format using UTF-8 encoding.

This function belongs to theGlobal object, which is supported by all major browsers.

grammatical

encodeURI(URIString);
parameterstypologyclarification
URIStringString typologyURI string to be encoded

This method returns an encoded URI string.

clarification

If you want to make a decision about using theencodeURI() function to decode the URI string, use thedecodeURI() function.

encodeURI() The function has 82 non-encoded characters!、#、$、'、(、)、*、+、,、-、.、/、:、;、=、?、@、_、~、0-9、a-z、A-Z 。

Use this function if you just want to encode a URI with special characters (such as Chinese) that is used as the request address.

If you want to pass the URI as a request parameter, then you can use theencodeURIComponent() function.encodeURIComponent() function encodes all characters.

typical example

// Original URI
var ftpUri = 'ftp://192.168.0.100/ shared folder ';


// Encoding URIs
var encodedFtpUri = encodeURI(ftpUri);
console.log(encodedFtpUri); // ftp://192.168.0.100/%E5%85%B1%E4%BA%AB%E6%96%87%E4%BB%B6%E5%A4%B9


// Decode URIs
var decodedFtpUri = decodeURI(encodedFtpUri);
console.log(decodedFtpUri); // ftp://192.168.0.100/ Shared folder

Object

JavaScriptObject Object, is the base class of all objects in JavaScript, that is, all objects in JavaScript are derived from Object object.Object object is mainly used to encapsulate arbitrary data into object form.

Objects can also be viewed as unordered collections of attributes, each of which is a name-value pair.Property names are strings, so we can think of objects as mapping from strings to values。

grammatical

constructor

new Object([value]);

Object Type Conversion Functions

Object([value]);
parametersclarificationtypology
valueOptional parameter, needs to be wrapped as a value of the objectany

Object.assign

Object.assign() method is used to copy the values of all enumerable own Properties from one or more source objects to the target object.

grammatical

Object.assign(target, ...sources);
parametersclarificationtypology
targettarget audienceobject
sourcessource objectobject

Returns the target object.

descriptive

If an attribute in the target object has the same key, the attribute will be overwritten by an attribute in the source object. Attributes in the source object that follow will similarly override attributes in the source object that precede them.

Object.assign method copies only the source object’s own enumerable properties to the target object.

This method uses the source object’s[[Get]] and the target object’s[[Set]]so it will call the relevantgetter respond in singingsetter. Thus, it assigns attributes, not just copies or defines new ones. If the merge source containsgetter, which may make it unsuitable to merge the new attributes into the prototype. In order to copy property definitions (including their enumerable properties) to the prototype, theObject.getOwnPropertyDescriptorrespond in singingObject.defineProperty 。

typical example

basic example
const a = { a: 1 };


const b = Object.assign({}, a);


console.log(b); // { a: 1 }

Object.create

Object.create() method is used to create a new object where the specified object is the prototype object.

grammatical

Grammar:

Object.create(o: object | null): any;
Object.create(o: object | null, properties: PropertyDescriptorMap & ThisType<any>): any;

Type declaration expansion:

interface PropertyDescriptor {
  configurable?: boolean;
  enumerable?: boolean;
  value?: any;
  writable?: boolean;
  get?(): any;
  set?(v: any): void;
}


interface PropertyDescriptorMap {
  [s: string]: PropertyDescriptor;
}


interface ThisType<T> {}

Parameter Description:

parametersclarificationtypology
oThe prototype object to which the newly created object pointsobject
propertiesOptional Parameters. Enumerable properties added to the newly created object (i.e., self-defined properties, not enumerated properties on the prototype chain)object

⚠️ attention (heed):

  • in the event thatproperties The parameters are notnull or object, then a TypeError exception is thrown.
  • Returns a new object with the specified prototype object and enumerable properties

typical example

class inheritance

// Shape = Super Class
function Shape() {
  this.x = 0;
  this.y = 0;
}


// Super Class Methods
Shape.prototype.move = function () {
  this.x += x;
  this.y += y;
  console.log('Shap moved');
};


// Retangle - Sub Class
function Retangle() {
  Shape.all(this); // call super constructor
}


// Subclasses inherit from parent classes
Retangle.prototype = Object.create(Shape.prototype);
Retangle.prototype.constructor = Retangle;


const rect = new Retangle();


console.log(rect instanceof Retangle);
// true
console.log(rect instanceof Shape);
// true

Object.defineProperties

Object.defineProperties() method is used to define Properties for an object and/or modify the Attributes of existing Properties.

grammatical

Object.defineProperties(O, Properties);
parametersclarificationtypology
OAdding or Modifying Target Objects for Propertiesobject
PropertiesObjects to define their enumerable properties or modified property descriptorsobject
Attributesdefault value
configurablefalse
enumerablefalse
valueundefined
writablefalse
getundefined
setundefined

Returns the changed object.

typical example

const abc = { a: 1, b: 2, c: 3 };


Object.defineProperties(abc, {
  a: {
    value: 'One',
    writable: false,
    enumerable: false,
    configurable: false,
  },
  e: {
    value: 4,
  },
  f: {
    value: 5,
  },
});


console.log(abc);
// {
// b: "Two",
// c: 3,
// a: "One",
// d: "Three",
// e: 4,
// f: 5,
// }


abc.a = 10;


console.log(abc.a);
// 'One'

Object.defineProperty

Object.defineProperty() method is used to define an own Property for an object and/or modify the Attributes of an existing Property.

grammatical

Object.defineProperty(O, P, Attributes);
parametersclarificationtypology
ODefining or Modifying the Target Object of a Propertyobject
PProperty key names to be definedstring
AttributesAttributes defined or modifiedobject

Returns the changed object.

typical example

const foo = {};


Object.defineProperty(foo, 'a', {
    value: 100,
    writable: true,
    enumerable: true,
    configurable: true
})


console.log(foo);
// { a: 100 }


const bar;


// Add properties and access descriptors
Object.defineProperty(foo, 'b', {
    get: function(){
        return foo
    },
    set: function(newValue){
        bar = newValue
    },
    enumerable: true,
    configurable: true,
})


foo.b = 99;


console.log(foo.b);
// 99

Object property hijacking

Iterate through all the properties of the hijacked object

const data = {
  a: 'a',
  b: 'b',
  c: 'c'
};


// Iterate over the object to hijack its property values
Object.keys(data).forEach(function(key) {
  Object.defineProperty(data, key, {
    enumerable: true,
    configurable: true,
    get: function() {
      console.log('GET')
    },
    set: function(value) {
      // We can perform additional operations when the value of a property changes.
      console.log('SET')
    }
  })
})

Object.entries

⭐️ ES2017 (ES8) New Features

Object.entries() method is used to enumerate the specified objects and return a two-dimensional array with elements consisting of an array of key-value pairs.

grammatical

Grammar:

Object.entries(obj);

Type declaration:

interface ObjectConstructor {
  values<T>(o: { [s: string]: T } | ArrayLike<T>): T[];


  values(o: {}): any[];
}

Parameter Description:

parametersclarificationtypology
objobject for enumerationobject

Return Value:

Returns an array of key-value pairs for the given object’s own enumerable Properties.

Methodological note

Given an array of key-value pairs of an object’s own enumerable properties, the arrangement and use of thefor-inThe loop returns the same order when iterating over the object, the difference being that thefor-in The loop also enumerates the properties in the prototype chain.

code example

const a = { foo: 1, bar: 2 };
Object.entries(a);
// [['foo', 1], ['bar', 2]]


Object.entries('foo');
// [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]


const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`);
  // "a 5", "b 7", "c 9"
}


Object.entries(obj).forEach(([key, value]) => {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});

Object.entries

⭐️ ES2017 (ES8) New Features

Object.entries() method is used to enumerate the specified objects and return a two-dimensional array with elements consisting of an array of key-value pairs.

grammatical

Grammar:

Object.entries(obj);

Type declaration:

interface ObjectConstructor {
  values<T>(o: { [s: string]: T } | ArrayLike<T>): T[];


  values(o: {}): any[];
}

Parameter Description:

parametersclarificationtypology
objobject for enumerationobject

Return Value:

Returns an array of key-value pairs for the given object’s own enumerable Properties.

Methodological note

Given an array of key-value pairs of an object’s own enumerable properties, the arrangement and use of thefor-inThe loop returns the same order when iterating over the object, the difference being that thefor-in The loop also enumerates the properties in the prototype chain.

code example

const a = { foo: 1, bar: 2 };
Object.entries(a);
// [['foo', 1], ['bar', 2]]


Object.entries('foo');
// [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]


const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`);
  // "a 5", "b 7", "c 9"
}


Object.entries(obj).forEach(([key, value]) => {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});

Object.getOwnPropertyDescriptor

Object.getOwnPropertyDescriptor() method to get one of the Attributes of the object’s own Property.

grammatical

Object.getOwnPropertyDescriptor(O, Property);
parametersclarificationtypology
OTarget object to be foundobject
PropertyProperty of the target objectstring

typical example

const foo = { a: 1 };


Object.getOwnPropertyDescriptor(foo, 'a');
// Object {
// 	value: "a",
// 	writable: true,
// 	enumerable: true,
// 	configurable: true,
// }

Object.getOwnPropertyDescriptors

⭐️ ES2017 (ES8) New Features

Object.getOwnPropertyDescriptors() method is used to get all the Attributes of an object’s own Property.

grammatical

Grammar:

Object.getOwnPropertyDescriptors(obj);

Type declaration:

interface ObjectConstructor {
  getOwnPropertyDescriptors<T>(
    o: T
  ): { [P in keyof T]: TypedPropertyDescriptor<T[P]> } & { [x: string]: PropertyDescriptor };
}


interface TypedPropertyDescriptor<T> {
  enumerable?: boolean;
  configurable?: boolean;
  writable?: boolean;
  value?: T;
  get?: () => T;
  set?: (value: T) => void;
}


interface PropertyDescriptor {
  configurable?: boolean;
  enumerable?: boolean;
  value?: any;
  writable?: boolean;
  get?(): any;
  set?(v: any): void;
}

Parameter Description:

parametersclarificationtypology
objObject for getting the Attributes of a Propertyobject

code example

const a = {
  name: 'Ben',
  get age() {
    return '18';
  },
};


Object.getOwnPropertyDescriptors(a);

Object.getPrototypeOf

Object.getPrototypeOf() method is used to get the prototype of the specified object (the internal[[Prototype]] (the value of the attribute).

grammatical

Object.getPrototypeOf(O);
parametersclarificationtypology
Otarget audienceobject

Returns the prototype object of the target object.

typical example

basic example

const proto = {};


const foo = Object.create(proto);
Object.getPrototypeOf(foo) === proto;
// true


const reg = /a/;
Object.getPrototypeOf(reg) === Regexp.prototype;
// true

Standard Built-In Objects

const foo = new Object();


Object.getPropertyOf(Object);
// f () { [native code] }
Object.getPropertyOf(Function);
// f () { [native code] }


Object.getPropertyOf(Object) === Function.prototype;
// true


const bar = new Object();
Object.prototype === Object.getPrototypeOf(bar);
// true
Obejct.prototype === Object.getPrototypeOf({});
// true

Object.is

Object.is() method is used to determine if two values are the same value.

grammatical

Object.is(value1, value2);
parametersclarificationtypology
value1Comparison value 1any
value2Comparison value 2any

Returns the result of a judgment expression.

descriptive

Determine if any of the following holds true, then the two values are the same:

  • Both values areundefined
  • Both values arenull
  • Both values aretrue maybefalse
  • Two values are strings of the same number of characters in the same order.
  • Two values point to the same object
  • Both values are numeric and
    • All positive zeros.+0
    • All negative zeros.-0
    • allNaN
    • Both divide by zero andNaN Other than the same number

This logic of equivalence judgment and the traditional== Operationally different.== operator will do to the operands on either side of it theimplicit type conversion, before the equivalence comparison is made, (hence the analogous"" == false be tantamount totrue phenomenon), butObject.is will not do this type conversion.

conflict with=== Operators are determined differently.=== Operators (and== Operator) to convert the numeric value-0 respond in singing+0 are considered equal and thatNumber.NaN not equal β‰ NaN。

typical example

Object.is(undefined, undefined);
// true


Object.is(null, null);
// true


Object.is(true, true);
// true


Object.is(100, 100);
// true


Object.is('foo', 'bar');
// false


Object.is([], []);
// false


Object.is(0, -0);
// false
Object.is(-0, -0);
// true
Object.is(NaN, 0 / 0);
// true

Object.keys

Object.keys() method is used to obtain an array of key names consisting of the enumerable Properties of the specified object itself.

grammatical

Object.keys(O);
parametersclarificationtypology
Ospecified objectobject

Returns an array of the key names of all enumerable Properties of the object.

descriptive

The order of the key names in the obtained array and the use of thefor The series of loop statements get the key names in the same order.

typical example

arrays

const foo = ['a', 'b', 'c'];


console.log(Object.keys(foo));
// console: ['0', '1', '2']

class array

const foo = { 0: 'a', 1: 'b', 2: 'c' };


console.log(Object.keys(foo));
// console: ['0', '1', '2']

unenumerable property

// getBar is a property which isn't enumerable
const foo = Object.create(
  {},
  {
    getBar: {
      value: function() {
        return this.bar;
      },
    },
  }
);


foo.bar = 1;


console.log(Object.keys(foo));
// ['bar']

Object.setPrototypeOf

Object.setPrototypeOf() method is used to set the prototype of a given object (i.e., the internal[[Prototype]] attribute) to another object ornull。

grammatical

Object.setPrototypeOf(O, proto);
parametersclarificationtypology
OThe object whose prototype is to be setobject
protoprototype objectobject

Returns the object after setting the prototype.

typical example

const foo = Object.setPrototypeOf({}, null);

code implementation

if (!Object.setPrototypeOf) {
  Object.setPrototypeOf = function() {};
}

Object.values

⭐️ ES2017 (ES8) New Features

Object.values() method is used to specify an array of all enumerable Property values for the object itself.

grammatical

Grammar:

Object.values(obj);

Type declaration:

interface ObjectConstructor {
  values<T>(o: { [s: string]: T } | ArrayLike<T>): T[];


  values(o: {}): any[];
}

Parameter Description:

parametersclarificationtypology
objspecified objectobject

Returns a collection of arrays from which the object can enumerate Property values.

Methodological note

The order of the keys in the returned array matches the combination of keys and values obtained using the loop statement.

code example

const obj = {
  a: '1',
  b: '2',
  c: '3',
};


console.log(Object.values(obj));
// ['1', '2', '3']

Object.prototype.hasOwnProperty

Object.prototype.hasOwnProperty method is used to detect whether the specified object has the specified Property in its own Properties.

grammatical

O.prototype.hasOwnProperty(V);
parametersclarificationtypology
VThe name of the Property string or Symbol to be detected.string/symbol

Returns whether the object contains a Boolean value for the specified Property.

descriptive

All objects that inherit from Object inherit from thehasOwnProperty Methods.

This method can be used to detect whether an object contains a specific self attribute; andin operator is different, this method ignores properties that are inherited from the prototype chain.

typical example

basic example

const foo = new Object();
foo.a = 'exist';


function change() {
  foo.b = foo.a;
  delete foo.a;
}


foo.hasOwnProperty('a');
// true


change();


foo.hasOwnProperty('b');
// false

Owned versus Inherited Properties

const foo = new Object();


foo.a = 'Hello world!';


foo.hasOwnProperty('a');
// true
foo.hasOwnProperty('toString');
// false
foo.hasOwnProperty('hasOwnProperty');
// false

Object.prototype.isPrototypeOf

Object.prototype.isPrototypeOf() method is used to test whether the specified object exists in the prototype chain of the target object.

grammatical

O.prototype.isPrototypeOf(V);
parametersclarificationtypology
VTarget object (searching up the prototype chain of that object)object

Returns a value of type Boolean specifying whether the object is in the prototype chain of the target object.

typical example

function Foo() {}
function Bar() {}
function Baz() {}


Bar.prototype = Object.create(Foo.prototype);
Baz.prototype = Object.create(Bar.prototype);


const baz = new Baz();


console.log(Baz.prototype.isPrototypeOf(baz));
// true


console.log(Bar.prototype.isPrototypeOf(baz));
// true


console.log(Foo.prototype.isPrototypeOf(baz));
// true


console.log(Object.prototype.isPrototypeOf(baz));
// true

Object.prototype.prototypeIsEnumerable

Object.prototype.prototypeIsEnumerable() method is used to detect whether the specified Property is enumerable.

grammatical

O.prototype.prototypeIsEnumerable(V);
parametersclarificationtypology
VThe name of the Property key to be testedstring

Returns a value of type Boolean indicating whether the specified Property key name is enumerable.

typical example

basic example

const foo = {};
const bar = [];


foo.a = 'is enumerable';
bar[0] = 'is enumerable';


foo.propertyIsEnumerable('a');
// true
bar.propertyIsEnumerable(0);
// true

Owned versus Inherited Properties

Properties in the prototype chain are notpropertyIsEnumerable Consider.

const a = [];


a.propertyIsEnumerable('constructor');


function b() {
  this.property = 'b';
}


b.prototype.firstMethod = function() {};


function c() {
  this.method = function method() {
    return 'c';
  };
}


c.prototype = new b();
c.prototype.constructor = c;


const d = new c();


d.arbitraryProperty = 'd';


d.prototypeIsEnumerable('arbitraryProperty');
// true
d.prototypeIsEnumerable('method');
// true
d.prototypeIsEnumerable('property');
// false


d.property = 'd';


d.prototypeIsEnumerable('property');
// true

Object.prototype.toString

Object.prototype.toString() method is used to represent the string of the specified object.

grammatical

O.prototype.toString();

A string representing the object.

descriptive

All values created by the standard built-in objects can be passed through thetoString() method to get a value of type String.

typical example

basic example

const foo = new Object();


foo.toString();
// [object Object]

Detecting object type

require the use ofFunction.prototype.call() respond in singingFunction.prototype.apply() is invoked in the form of a call, with the object to be detected entered as the first parameter.

const toString = Object.prototype.toString();


toString.call(new Date());
// [object Date]


toString.call(new String());
// [object String]


toString.call(Math);
// [object Math]


// Since JavaScript 1.8.5
toString.call(undefined);
// [object Undefined]
toString.call(null);
// [object Null]

Object.isExtensible

Object.isExtensible() method is used to detect whether the specified object is extensible.

grammatical

Object.isExtensible(O);
parametersclarificationtypology
OSpecify the object to be used for detectionobject

Returns a value of type Boolean indicating whether the object used for testing is extensible.

descriptive

By default, objects are extensible: that is, new properties can be added to them.

Object.preventExtensions、Object.sealmaybeObject.freezemethods can all mark an object as non-extensible.

typical example

let foo = {
  a: 1,
};
console.log(Object.isExtensible(foo));
// true


foo.b = 2;


console.log(foo);
// {a: 1, b: 2}


console.log(Object.preventExtensions(foo));
// { a: 1, b: 2}


// The assignment statement fails silently because the object foo is not allowed to be extended.
foo.c = 3;


console.log(Object.isExtensible(foo));
// false


console.log(foo);
// { a: 1, b: 2}

Function

The Function constructor is passed through thenew Create a new Function object. In JavaScript, every function is actually a Function object.

grammatical

constructor

new Function ( [ argName1 [, argName1 [, argNameN... [, funcBody ]]]] )

Function Type Conversion Functions

Function ( [ argName1 [, argName1 [, argNameN... [, funcBody ]]]] )
parametersclarificationtypology
argName1Name of the first parameter of the definitionstring
argName2Name of the second parameter of the definitionstring
argNameNThe name of the Nth parameter of the definition, which can be any number of parameters.string
funcBodyThe body of the defined function, i.e. the execution code inside the function, defaults to the empty string ("")string

Function() will take the incomingThe last parameteras the execution code for the function definition, and all previous arguments are in turn used as arguments to the function definition.

  • If no arguments are specified, the function has no defined argument list and the function’s execution code is empty.
  • If only one parameter is specified, that parameter will be treated as the execution code of the function. If you want to define one parameter and the execution code to be empty, pass in two parameters and just make the second parameter an empty string:new Function("argName1", "")。

Function() The return value is of type Function, which returns a function object.

Function.prototype.apply

Function.prototype.apply method is used to specify that the function call points to thethis pointer and provides a list of parameters of class array type as arguments to the specified function.

grammatical

Grammar:

apply(thisArg: any, argArray?: any): any;

Parameters:

parametersclarificationtypology
thisArgOptional parameters. The parameter to point to when calling the functionthis Pointer./
argArrayOptional parameters. List of arguments to the calling function.Array | TypedArray

descriptive

Function.prototype.apply together withFunction.prototype.call are very similar, the difference being in the way the parameters are provided, theapply Use an array of arguments instead of a list of arguments.

You can use thearguments object asargArray Parameters.arguments is a local variable of a function that can be used as all unspecified parameters of the called object. This way, you can use theapply method would not need to know all the parameters of the object being called. You can use thearguments to pass all the parameters to the called object. The called object is then responsible for processing these parameters.

typical example

Array element additions

utilizationArray.prototype.pushcan append elements to an array, and the method can take a variable number of arguments.

But if, however, we need to pass an array to append to the array, it will actually add that array as a single element rather than adding the elements individually, so we end up with an array within an array.

In this case, while it’s possible to get a better idea of what’s going on with theArray.prototype.concatimplements the behavior we want, but instead of appending to the original array, it actually creates and returns a new array.

And we can do that with theFunction.prototype.apply Realize that need.

const foo = [];
const bar = [1, 2, 3, 4];


foo.push.apply(foo, bar);


console.log(foo);
// [1, 2, 3, 4]

Built-in Function Usage

It is possible to useFunction.prototype.apply Implement the use of built-in functions for tasks that would otherwise require traversing array variables.

The following example uses theMath.max respond in singingMath.min to find the maximum/minimum value in an array.

const foo = [2, 4, 6, 8, 10];


const max = Math.max.apply(null, foo);
const min = Math.min.apply(null, foo);

⚠️ attention (heed): Use the above to callFunction.prototype.applyIn this case, there is a risk of exceeding the JavaScript engine’s parameter length limit. When passing a function a very large number of arguments (say, 10,000), it is very likely to cause an out-of-bounds problem, and this threshold depends on the JavaScript engine (it is hard-coded in the core of JavaScript).The number of parameters is limited to 65536), because this limit (and indeed any behavior that uses large stack space) is unspecified, some engines will throw exceptions. Worse yet other engines will simply limit the number of arguments passed into the method, resulting in lost arguments.

If the parameter array is likely to be large, it can be handled using the following strategy: chunk the parameter array and pass it into the target method in a loop.

function minOfArray(arr) {
  var min = Infinity;
  var QUANTUM = 32768;


  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
    var submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len)));
    min = Math.min(submin, min);
  }


  return min;
}


var min = minOfArray([5, 6, 2, 3, 7]);

Function.prototype.call

Function.prototype.call method is used to specify that the function call points to thethis pointers and provide the parameters as arguments to the specified function, respectively.

grammatical

Grammar:

call(thisArg: any, ...argArray: any[]): any;

parameters

parametersclarificationtypology
thisArgOptional parameters. The parameter to point to when calling the functionthis Pointer.
argsOptional parameters. List of arguments to the calling function.

typical example

function Product(name, price) {
  this.name = name;
  this.price = price;
}


function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}


function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}


const cheese = new Food('cheese', 5);
const robot = new Toy('robot', 40);


console.log(cheese);
// {
//   category: "food",
//   name: "cheese",
//   price: 5,
// }
console.log(robot);
// {
//   category: "toy",
//   name: "robot",
//   price: 40,
// }

Function.prototype.bind

Function.prototype.bind method creates a new function in thebind() When called, this new function’sthis designated asbind() the first parameter of the new function, and the rest of the parameters will be used as arguments to the new function for the call.

grammatical

Grammar:

bind(thisArg: any, ...argArray: any[]): any;

parameters

parametersclarificationtypology
thisArgOptional parameters. The parameter to point to when calling the functionthis Pointer./
arg1,arg2,…Optional parameters. Arguments that are prepended to the argument list of the bound function when the target function is called.any

descriptive

Function.prototype.bind function creates a newBinding Functions(Bound Function, BF). A Bound Function is an Exotic Function Object (a term used in ECMAScript 2015) that wraps the original function object. Calling a bound function usually results in the execution ofwrapper function (computing)。

The bind function has the following internal properties:

  • [[BoundTargetFunction]]: Wrapped function objects
  • [[BoundThis]]: Always call the wrapper function asthis The value of the value pass.
  • [[BoundArguments]]: list, the argument list is preferentially populated with list elements in any call to the wrapper function.
  • [[Call]]: Execute the code associated with this object. Called via a function call expression. The argument to an internal method is athis value and a list containing the arguments passed to the function via the calling expression.

When the bind function is invoked, it calls the[[BoundTargetFunction]] Internal methods on the[[Call]]It’s like this.Call(boundThis, args). Among other things.boundThis be[[BoundThis]],args be[[BoundArguments]] Plus a list of arguments passed through the function call.

Binding functions can also be usednew operator constructor, it will behave as if the target function has been constructed. The providedthis values are ignored, but the predicate arguments are still provided to the simulation function.

typical example

Creating Binding Functions

Function.prototype.bind() The simplest use is to create a function that, no matter how it is called, has the samethis references.A common mistake made by JavaScript novices is to take a method out of an object and call it, expecting the method’sthis is the original object (e.g., passing this method in a callback). The original object will generally be lost if no special handling is done. Creating a bind function with the original object based on this function solves this problem neatly.

this.a = '100';


const foo = {
  a: '99',
  getA: function () {
    return this.a;
  },
};


foo.getA();
// '99'


const retrieveA = foo.getA;


retrieveA();
// '100'


const boundGetA = retrieveA.bind(foo);


boundGetA();
// '99'

(math.) partial function

Function.prototype.bind() Another of the simplest uses of methods is to make a function have preset initial parameters. Simply pass these parameters (if any) as thebind() The parameters are written in thethis followed by them. When the bind function is called, these arguments are inserted at the beginning of the argument list of the target function, and the arguments passed to the bind function follow them.

const foo = function (a, b, c, d, e, f) {
  console.log(a, b, c, d, e, f);
};


// Preset three parameters 1 2 3 -> corresponding to foo parameters a b c
const bar = foo.bind(null, 1, 2, 3);


bar(4, 5, 6);
// 1 2 3 4 5 6

Matching Timer

By default, using thewindow.setTimeout whenthis keyword will point to the Window object. When a method of a class requires thethis When pointing to an instance of a class, you may need to explicitly put thethis Binding to a callback function will not lose the reference to that instance.

function LaterBloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}


LaterBloomer.prototype.bloom = function () {
  window.setTimeout(this.declare.bind(this), 1000);
};


LateBloomer.prototype.declare = function () {
  console.log('I am a beautiful flower with ' + this.petalCount + ' petals!');
};


const flower = new LateBloomer();


flower.bloom();

String

A String object is an object used forstring (computer science) or acharacter sequence The constructor of the

The String object is the object form of a text string.The String object allows manipulating and formatting text strings as well as determining and locating substrings within a string.

grammatical

constructor

new String([value]);

String Type Conversion Functions

String([value]);
parameterstypologyclarification
valueArbitrary typeAny value that can be converted to a string.

clarification

template literal

As of ECMAScript 2015, string literals can also be calledtemplate literal:

const w = 'world'`Hello ${w}!`;

String.fromCharCode

static (as in electrostatic force)String.fromCharCode() method returns a string created from the specified sequence of UTF-16 code units.

grammatical

String.fromCharCode(num1 [, num2 [, num3 ...[, numN]]]);

Parameters:

  • num: A series of numbers in UTF-16 code units. The range is from 0 to 65535 (0xFFFF) between. Greater than0xFFFF of the number will be truncated. No validity check will be performed.

usage example

String.fromCharCode(65, 66, 67);
// ABC


String.fromCharCode(0x2014);
// -

String.prototype.charAt()

charAt() method returns the specified character from a string.

grammatical

str.charAt(index);
parametersclarificationtypology
indexAn integer between 0 and the length of the string minus one. (0~length-1). If no index is provided, the default value is 0.number

clarification

Characters in the string are indexed from left to right:

  • The index value of the first character is 0
  • The last character (assuming that it is in the stringstringNamein) has an index value ofstringName.length - 1
  • If the specifiedindex value is out of the range, then an empty string is returned''

typical example

const javascript = 'JAVASCRIPT';


javascript.charAt();
// J
javascript.charAt(0);
// J
javascript.charAt(1);
// A
javascript.charAt(2);
// V
javascript.charAt(3);
// A
javascript.charAt(4);
// S
javascript.charAt(5);
// C
javascript.charAt(6);
// R
javascript.charAt(7);
// I
javascript.charAt(8);
// P
javascript.charAt(9);
// T
javascript.charAt(100);
// ''

String.prototype.charCodeAt()

charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index (in the case where the Unicode encoding unit represents a single UTF-16 encoding unit, the UTF-16 encoding unit matches the Unicode encoding unit. But in the case of – for example, Unicode encoding unit >0x10000 (such as this one – can’t be represented by a UTF-16 encoding unit on its own, it can only match the first encoding unit of a Unicode proxy pair). If you want the entire codepoint value, use thecodePointAt()。

grammatical

str.charCodeAt(index);
parametersclarificationtypology
indexAn integer greater than or equal to 0 and less than the length of the string. If it is not a numeric value, it defaults to 0.number

The return value represents the Unicode encoding of the character at the specified index of the string object; if the index is out of range, the return value isNaN。

clarification

Unicode code points range from 0 to 1114111 (0x10FFFF). The first 128 Unicode code units are the same as the ASCII character code.

Attention.charCodeAt always returns a value less than 65536. This is because the higher code point is represented by a pair of (lower valued) surrogate pseudo-characters to form a real character. Therefore, in order to view or reproduce the full character set of 65536 and higher encoded characters, thecharCodeAt(i) Get the value of thecharCodeAt(i+1) value, or instead get the value of thecodePointAt(i) The value of the

If the specifiedindex is less than 0 or not less than the length of the string, thecharCodeAt come (or go) backNaN。

typical example

The following example describes the Unicode values returned for different indexing cases:

'ABC'.charCodeAt(0);
// 65
'ABC'.charCodeAt(1);
// 66
'ABC'.charCodeAt(2);
// 67
'ABC'.charCodeAt(3);
// NaN

String.prototype.concat()

concat() function is used to splice the current string with the specified string and return the spliced string.

grammatical

str.concat( string2, string3 [, ..., stringN] )
parametersclarificationtypology
str2...strNMultiple strings concatenated with the original string.string

concat() The return value of the function isString type, whose return value is a spliced string.

concat() Functions are equivalent to operators+, for example:str.concat(str1, str2) tantamountstr + str1 + str2。

clarification

concat method concatenates and merges one or more strings with the original string to form a new string and returns it.concat method does not affect the original string.

typical example

The following example demonstrates how to merge multiple strings with the original string into a new string

var hello = 'Hello, ';


hello.concat('Kevin', ' have a nice day.');
// Hello, Kevin have a nice day.

It is recommended to use the assignment operator (+ maybe+=) instead of the stringconcat Methods.

var hello = 'Hello, ';


hello += 'world';


console.log(hello);
// Hello, world

String.prototype.endsWith()

endsWith() Used to determine if the current string is a substring of another given substringwind up of the program, according to the result of the judgment to return thetrue maybefalse。

grammatical

str.endsWith( searchString [, length] )
parametersclarificationtypology
searchStringSubstring to be searchedstring
lengthact asstr lengthsnumber

This method helps you determine if a string is at the end of another string. This method is case sensitive.

clarification

concat method concatenates and merges one or more strings with the original string to form a new string and returns it.concat method does not affect the original string.

typical example

const str = 'Hello world!';


console.log(str.endsWith('world!'));
// true


console.log(str.endsWith('abc'));
// false

String.prototype.includes()

includes() method is used to determine whether a string is contained in another string, returning, depending on the situation, thetrue maybefalse。

grammatical

str.includes( searchString [, startIndex] )
parametersclarificationtypology
searchStringString to be searched instring
startIndexDevelops a search substring from the current string at the specified index, defaults to 0 and includes the index.number

This method helps you determine whether a string contains another string.

This method searches for matching strings that are case-sensitive.

typical example

var str = 'To be, or not to be, that is the question.';


console.log(str.includes('To be'));
// true


console.log(str.includes('question'));
// true


console.log(str.includes('nonexistent'));
// false


console.log(str.includes('To be', 1));
// false


console.log(str.includes('TO BE'));
// false

String.prototype.indexOf()

indexOf() function is used to find the position of the first occurrence of the substring in the current string.

grammatical

str.indexOf( searchValue[, startIndex])
parametersclarificationtypology
searchValueThe substring to be looked up.string
startIndexOptional, the starting index to look up in the current string, default is 0.number

indexOf() The return value of the method is of type Number, which returns the starting position (index) of the first time the substring is found in the current string.

typical example

Characters in a string are indexed from left to right. The index of the first character is 0. The stringstringName The index of the last character ofstringName.length - 1。

'Blue Whale'.indexOf('Blue');
//  0
'Blue Whale'.indexOf('Blute');
// -1
'Blue Whale'.indexOf('Whale', 0);
//  5
'Blue Whale'.indexOf('Whale', 5);
//  5
'Blue Whale'.indexOf('', 9);
//  9
'Blue Whale'.indexOf('', 10);
// 10
'Blue Whale'.indexOf('', 11);
// 10

distinguishing capitals from lower case letters

The following example defines two string variables.

Both variables contain the same string, except that some characters in the second string are capitalized. The firstlog method outputs 19. But since theindexOf methodologiesdistinguishing capitals from lower case lettersand therefore will not be in themyCapString String found inβ€œcheddar"The second resultlog method outputs -1.

var myString = 'brie, pepper jack, cheddar';
var myCapString = 'Brie, Pepper Jack, Cheddar';


console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'));
// 19
console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
// -1

Counting the number of letters in a string

utilizationindexOf Counting the number of times a letter appears in a string

In the following example, the setting of thecount to record the letter e in the stringstr The number of occurrences in the

let str = 'To be, or not to be, that is the question.';
let count = 0;
let cur = str.indexOf('e');


// When cur is -1, there are no more substrings to retrieve.
while (cur !== -1) {
  count++;
  cur = str.indexOf('e', cur + 1);
}


console.log(count); // displays 4

Detecting the presence of a character

When testing whether a string exists in another string, the following methods can be used:

'Blue Whale'.indexOf('Blue') !== -1;
// true


'Blue Whale'.indexOf('Bloe') !== -1;
// false

String.prototype.match()

match()function is used to use the specified regular expression pattern in the current string to match the search, and return an array of search results.

grammatical

str.match(regexp);
parametersclarificationtypology
regexpAn instance of a RegExp object containing a regular expression pattern. Can also be a variable name or string containing the regular expression pattern.RegExo

If the parameterregExp is not a regular expression object (RegExp), but a string type, thematch() The string is first passed to the RegExp constructor, which converts it to a RegExp object.

match()The return value of the method is of type Array, and the members of the return array depend on whether the specified regular expression pattern has a global flag or not.g。

  • If the parameterregExpNo global flaggfollowmatch()The function looks for only the first match and returns an array containing the results of the search, the array object contains the following members:
    • indexing0: Holds the first matched substring.
    • causalityindex: The starting index position of the matching text in the string.
    • causalityinput: the entire string object (str)。

In IE 6 ~ IE 8, this array also has additionallastIndex attribute that stores the next position of the last character of the matched text.

  • If the parameterregExpWith global flagsgfollowmatch()function looks for all matches and returns an array that no longer has theindexandinputattribute, where the array elements are all the matched substrings, of the form:

    • indexing0: Holds the first matched substring (if it exists).
    • indexing1: Holds the second matching substring (if it exists).
    • ……
    • indexingN-1: Holds the Nth matching string (if it exists).
  • match() function returns if it does not find any matches.null。

clarification

  • If you need to know if a string matches a regular expression RegExp, you can use theString.prototype.search()。
  • If you just need the first match, you may want to use theRegExp.prototype.exec()。
  • If you want to get the capture group and set the global flag, you need to use theRegExp.prototype.exec() 。

typical example

In the following example, match is used to find"Hello world!" followed by 1 or more numeric characters, followed by a decimal point and the numeric character 0 or more times. Regular expressions containi flag, so case is ignored.

var str = 'Hello world!';


str.match();
// ["", index: 0, input: "Hello world!", groups: undefined]


str.match(/\b\w/);
// ["H", "w"]


str.match(/\w(?=r)/g);
// null


str.match(/\w[^\w]/g);
// ["o", "d!"]

Global and case-insensitive modes

The following example shows howmatch() utilizationglobal respond in singingignore case Logo.A-E、a-e will be returned as elements of an array.

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matchArray = str.match(regexp);


console.log(matchArray);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

not passing parameters

var str = 'Nothing will come of nothing.';


str.match();
// [""]

Determine if it is a microsoft browser

const isWeixin = function() {
  const ua = naviagtor.userAgent.toLowerCase();


  if (ua.match(/MicroMessenger/i) === 'micromessenger') {
    return true
  } else {
    return false;
  }
}

String.prototype.replace()

replace() function is used to use the specified string to replace the current string matching the specified regular expression pattern of the substring, and return to complete the replacement of the string.

grammatical

str.replace(pattern, replacement);
parametersclarificationtypology
patternAn instance of the RegExp object for the specified regular expression pattern. Can also be a string.string / RegExp
replacementThe string to be used for replacement, or a function that returns the replacement string.string / function

A new string that partially or fully matches the string replaced by the substitution pattern.

descriptive

  • If the parameterpattern is a string, thenreplace() function will do an exact match based directly on the string, without trying to convert it to a regular expression, and theReplace only the first match to substring of
  • parametersreplacement You can use the following to$ beginningMatching variables to dynamically determine the content of the string to be used for substitution (parameterpattern is a regular expression)
characterdescriptive
$nIf the first argument isRegExp object, andn is a non-negative integer less than 100, then inserting the firstn The string matched by the parentheses.
$&Inserts a matching substring.
`$“Inserts the left side of the currently matched substring.
$'Inserts the right side of the currently matched substring.
$$Insert a$。

When performing a global search-and-replace, the regular expression needs to include theg Logo.

  • Specify a function as an argument

You can specify a function as the second argument. In this case, the function is executed when the match is executed. The return value of the function is the replacement string. (Note: the special substitution arguments mentioned above cannot be used here.) Also note that if the first argument is a regular expression and it is a global match pattern, then this method will be called multiple times, for each match.

Here are the parameters for this function:

variable namerepresentative value
matchMatching substrings. (Corresponding to the above\$&。)
p1,p2, …providedreplace() The first argument to the method is aRegExp object, then it represents the firstn The string matched by the parentheses. (Corresponds to the above$1,$2etc.)
offsetThe offset of the matched substring within the original string. (For example, if the original string is'abcd'The sub-string that matches is'bc'If the parameter is 1, then this parameter will be 1)
stringThe original string being matched.

The precise number of parameters depends on thereplace()is a regular expression object, and how many parenthesized substrings are specified in the regular expression.

typical example

code example

In the following example, thereplace() Regular expressions and case-ignoring tags are used.

var str = 'Twas the night before Xmas...';


var newstr = str.replace(/xmas/i, 'Christmas');


console.log(newstr);
// Twas the night before Christmas...


var str = 'Hello world!';


// Replace the character 'lo' with '**'.
str.replace('lo', '**');
// "Hel** world!"


// Replace all 'h' with '**' (global, ignore case)
str.replace(/h/ig);
 // '**ello world!'


// Replace two letters located before a word boundary with '**'
str.replace(/\w{2}\b/g, '**');
 // "Hel** wor**!"


// Replace the two letters located at the start position and the word boundary with '**' (no matches)
str.replace(/^\w{2}\b/g/, '**');
// "Hello world!"


// Add "**" to all letters that are two consecutive letters and are not followed by the letter 'l'.
// The "$1" here is what the first parenthesized sub-expression in the regular expression matches.
str.replace(/(\w{2}(?!l))/g, '**$1');
// "He**llo **wo**rld!"

String.prototype.slice()

slice() method extracts a part of the string and returns a new string.

grammatical

str.slice( startIndex [, endIndex] )
parametersclarificationtypology
startIndexIndex pointing to the beginning of the specified part of the string.number
endIndexOptional, an index to the end of the specified portion of the string (excluding this index), defaults to the end of the string.number

Returns a new string extracted from the original string

descriptive

slice() The function always starts at indexstartIndex Copy toendIndex The characters indicated, but not theendIndex Characters on the index.

  • in the event thatstartIndex is negative, it is treated asstr.length + startIndex。
  • If omittedendIndex, then it will be extracted all the way to the end of the string.
  • in the event thatendIndex is negative, it is treated asstr.length + endIndex。
  • in the event thatendIndex less than or equal tostartIndex, then no characters are copied and the empty string is returned.

typical example

code example

var str = 'abcdefghij';


// start index omitted i.e. extraction from 0, end index omitted i.e. extraction to the end of the string
str.slice(); // 'abcdefghij'


// start index 0, end index omitted i.e. extract to the end of the string
str.slice(0);
// 'abcdefghij'


// Starts at index 0, ends at index 2
str.slice(0, 2);
// 'ab'


// start index is -3, i.e. negative, i.e. -3+10=7, end index omitted, i.e. extracted to the end of the string
str.slice(-3);
// 'hij'


// Start at index 0, end at -3 i.e. -3+10=7
str.slice(0, -3);
// 'abcdef'


// The start index is -3, i.e. -3+10=7, the end index is -1+10=9.
str.slice(-3, -1);

String.prototype.split()

split() function is used to use the specified separator to split the string, and return to split a number of substrings after the composition of the array.

grammatical

str.split( [separator [, limit]] )
parametersclarificationtypology
separatorSpecifies a string indicating the point at which each split should occur.separator Can be a string or a regular expression. If the plain text separator contains more than one character, the entire string must be found to represent the split point. If the separator is omitted or does not appear in str, the returned array contains an element consisting of the entire string. If the separator is the empty string, an array of each character in the original str string is returned.string / RegExp
limitOptional, an integer that limits the number of split segments returned. When this parameter is supplied, thesplit method splits the string at each occurrence of the specified separator, but stops when the limit entry has been placed in the array. If the end of the string is reached before the specified limit is reached, it may still contain fewer entries than the limit. No remaining text is returned in the new array.number
  • When the separator is found, it is removed from the string and an array of substrings is returned.

  • If the separator is not found or is omitted, the array contains an element consisting of the entire string.

  • If the separator is the empty string, the string is split between each character.

  • If the separator appears at the beginning or the end of the string, or both separately, it begins and ends with the empty string, the end, or both, respectively. Thus, if the string consists of only one instance of the separator, the array consists of two empty strings.

  • If the separator is a regular expression containing capture brackets, the results of the capture brackets (including any undefined results) will be spliced into the output array each time the separator matches. However, not all browsers support this feature.

  • Returns an array containing an empty string when the string being looked up is empty, not an empty array if both the string and the separator are empty strings.

descriptive

If providedlimit parameter, the array returned by this function contains at mostlimit elements. If the parameterlimit is negative, the parameter will be omitted. If thelimitfollowsplit() The function does not consider the length until the split is complete. If thelimit is 0, an empty array is returned.

typical example

code example

'abcd'.split();
// ["abcd"]
'abcd'.split('b');
// ["a", "cd"]
'abcd'.split('a');
// ["", "bcd"]
'abcd'.split('d');
// ["abc", ""]
'abcd'.split('abcd');
// ["", ""]
'abcd'.split('');
// ["a", "b", "c", "d"]
'abcd'.split(' ');
// ["abcd"]


''.split();
// [""]
''.split('');
// []
''.split(' ');
// [""]

String.prototype.toLowerCase()

toLowerCase() function forConverts all letters of the current string to lowercase and returns the converted stringThis function is based on the regular Unicode case mapping. This function converts based on regular Unicode case mapping.

grammatical

str.toLowerCase();

descriptive

toLowerCase Converts the string value from which the method was called to lowercase form and returns it.toLowerCase() method does not affect the value of the string itself; it returns the new string.

typical example

var abc = 'ABC';


abc.toLowerCase();
// 'abc'

String.prototype.toUpperCase()

toUpperCase() function forConverts all letters in the current string to uppercase and returns the converted stringThis function is based on the regular Unicode case mapping. This function converts based on regular Unicode case mapping.

grammatical

str.toUpperCase();

descriptive

toUpperCase Converts the value of the string from which the method was called to uppercase form and returns it.toUpperCase method does not affect the value of the string itself; it returns the new string.

typical example

var abc = 'abc';


abc.toUpperCase();
// 'ABC'

Array objects

Array object when used to construct an array of global objects, similar to when similar to the list of higher-order objects.

Array Objects are mainly used to store multiple data items, and the data can be of any type.

All major browsers support this object.

grammatical

literal amount

[element0, element1, ..., elementN]

Array Type Conversion Functions

Array(element0, element1, ..., elementN)

constructor

new Array(element0, element1, ..., elementN)


new Array(arrayLength)

Array.from()

⭐️ ES2015 (ES6) New Features

Array.from() method is used to convert a class array object or an iterable object into a new array instance.

grammatical

Grammar:

Array.from(arrayLike [, mapfn [, thisArg]])

Type declaration:

interface ArrayLike<T> {
  readonly length: number;
  readonly [n: number]: T;
}


interface ArrayConstructor {
  from<T>(arrayLike: ArrayLike<T>): T[];


  from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
}

Parameter Description:

parametersclarificationtypology
arrayLikePseudo-array objects or iterable objects that you want to convert to arraystyped array
mapfn(Optional) If specified, this callback function is executed for each element in the new array.function
thisArg(Optional) Execute callback functionmapFn hourthis boyfriendobject

Return Value:

Returns a new array instance.

Methodological note

  • Subjects with both of the following conditions can be passed

    Array.from()
    

    method into a real array:

    • Class array objects: i.e., objects that havelength attribute and a number of indexed attributes of an arbitrary object
    • Iterable objects: i.e. objects deploying the Iterator interface, which can fetch elements of an object, such asMap respond in singingSet et al. (and other authors)
  • Array.from() method has an optional parametermapfnwhich allows you to execute it again on the last generated arrayArray.prototype.map method before returning. In other words, theArray.from(arrayLike, mapfn, thisArg) would be equivalent toArray.from(arrayLike).map(mapfn, thisArg) , unless the creation is not a usable intermediate array. This is useful for some subclasses of arrays, such as for thetyped arrayis important because the values of the intermediate arrays are not used in the call to themap() When it needs to be of the proper type.

  • from() (used form a nominal expression)length attribute is 1, i.e.Array.from.length === 1。

  • In ES2015.Class The syntax allows us to add a new type to a built-in type (e.g.Array) and custom classes with new subclasses (e.g. calledSubArray). These subclasses also inherit static methods from the parent class, such as theSubArray.from()The method is called to return the subclassSubArray Instead of an instance ofArray Examples of.

code example

basic usage

const bar = ['a', 'b', 'c'];


Array.from(bar); // ["a", "b", "c"]


Array.from('foo'); // ["f", "o", "o"]

Array.isArray()

Array.isArray() method is used to determine if a value is an array type.

grammatical

Grammar:

Array.isArray(arg);

Type declaration:

interface ArrayConstructor {
  isArray(arg: any): arg is any[];
}


declare var Array: ArrayConstructor;

Parameter Description:

parametersclarificationtypology
argValue to be detectedany

Return Value:

If the object isArray instance, then it returns thetrue ; otherwisefalse。

code example

The following function calls all returntrue

Array.isArray([]);


Array.isArray([1]);


Array.isArray(new Array());


Array.isArray(Array.prototype);

Little known fact: actuallyArray.prototype is also an array.

Array.isArray(Array.prototype);

The following function calls all returnfalse。

Array.isArray();


Array.isArray({});


Array.isArray(null);


Array.isArray(undefined);


Array.isArray(17);


Array.isArray('Array');


Array.isArray(true);


Array.isArray(false);


Array.isArray({ __proto__: Array.prototype });

Array.prototype.concat()

Array.prototype.concat() method is used to merge two or more arrays. This method does not change the existing array, but returns a new array.

grammatical

Grammar:

const new_array = old_array.concat( item1[, itemN ] )

Type declaration:

interface ConcatArray<T> {
  readonly length: number;
  readonly [n: number]: T;
  join(separator?: string): string;
  slice(start?: number, end?: number): T[];
}


interface Array<T> {
  concat(...items: ConcatArray<T>[]): T[];


  concat(...items: (T | ConcatArray<T>)[]): T[];
}

Parameter Description:

parametersdescriptivetypology
item1Data item added to the end of the current arrayany
itemNAdditional items to be added to the current array at the end, there can be more than one.any

Return Value:

Returns the new mergedArray Example.

Methodological note

concat method creates a new array of the elements of the object being called, with each parameter in the order of the elements of that parameter (if the parameter is an array) or the parameter itself (if the parameter is not an array). It does not recurse into nested array arguments.

concat The method does not changethis or any array provided as an argument, but instead returns ashallow copy, which contains a copy of the same elements that were combined with the original array. The elements of the original array will be copied into the new array as follows:

  • object reference (not the actual object):concat Copies the object reference into a new array.Both the original and new arrays refer to the same objects. That is, if the referenced object is modified, the change is visible to both the new array and the original array. This includes elements that are also array parameters of the array.
  • Data types such as strings, numbers and booleans (notString,Number respond in singingBoolean (Object):concat Copies the values of strings and numbers into a new array.

attention (heed): Arrays/values remain unchanged when concatenated. In addition, any operations on the new array (only if the elements are not object references) will have no effect on the original array and vice versa.

code example

Joining two arrays

The following code merges two arrays into a new one.

const alpha = ['a', 'b', 'c'];
const numeric = [1, 2, 3];


alpha.concat(numeric);
// Outputs: ['a', 'b', 'c', 1, 2, 3]

Array.prototype.indexOf()

Array.prototype.indexOf() method is used to find the location of the first occurrence of the specified character in an array member.

grammatical

Grammar:

arr.indexOf( searchElement [, fromIndex] )

Type declaration:

interface Array<T> {
  indexOf(searchElement: T, fromIndex?: number): number;
}

Parameter Description:

parametersclarificationtypology
searchElementArray elements to findany
fromIndexOptional, the starting index of the search in the current string, default is 0number

Return Value:

Returns the starting position (index) of the first lookup of an array element in the current array

Methodological note

This method uses Strict Equality (either Absolute Equality===or the Triple-equals operator is based on the same approach) to determine the relationship between the element being looked up and the elements contained in the array.

code example

basic usage

var arr = [1, 2, 3, 4, 5];


arr.indexOf(1);
// 0
arr.indexOf(7);
// -1
arr.indexOf(4, 2);
// 3
arr.indexOf(3, -1);
// -1
arr.indexOf(3, -3);
// 2

Array.prototype.join()

Array.prototype.join() method concatenates all members of an array (or array-like object) into a string.

grammatical

Grammar:

const str = arr.jon(separator);

Type declaration:

interface Array<T> {
  join(separator?: string): string;
}

Parameter Description:

parametersclarificationtypology
separatorCharacters that concatenate elements of an array into a stringstring

Return Value:

Returns a string concatenated with all array members. If the length of the array is 0, the empty string is returned.

Methodological note

All array members are converted to strings, which are then concatenated with a separator. If the elements areundefined ornull, then it will be converted to an empty string.

code example

basic usage

const arr = ['1', '2', '3', '4', '5'];


// Default comma delimiter without passing parameters
arr.join();
// '1,2,3,4,5'


arr.join(', ');
// '1, 2, 3, 4, 5'


arr.join(' + ');
// '1 + 2 + 3 + 4 + 5'


arr.join('');
// '12345'

Array.prototype.flat()

⭐️ ES2019 (ES10) New Features

Array.prototype.flat() method recursively traverses the array to a specifiable depth and returns all the elements in the traversed subarray merged with the elements in the traversed subarray as a new array.

grammatical

Grammar:

arr.flat([depth]);

Type declaration:

type FlatArray<Arr, Depth extends number> = {
  done: Arr;
  recur: Arr extends ReadonlyArray<infer InnerArr>
    ? FlatArray<
        InnerArr,
        [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]
      >
    : Arr;
}[Depth extends -1 ? 'done' : 'recur'];


interface ReadonlyArray<T> {
  flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[];
}


interface Array<T> {
  flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[];
}

Parameter Description:

parametersclarificationtypology
depth(Optional parameter) Specifies the depth of the structure of the nested array to be extracted; the default value is 1.number

Return Value:

Returns a new array containing all the elements of the array and subarrays.

code example

basic usage

const arr1 = [0, 1, 2, [3, 4]];


console.log(arr1.flat());
// exprected output: [0, 1, 2, 3, 4]


const arr2 = [0, 1, 2, [[[3, 4]]]];


console.log(arr2.flat());
// exprected output: [0, 1, 2, [ 3, 4]];

Array.prototype.every()

every() method iterates through each member of the array, determining through a callback function whether all members satisfy a particular condition.

grammatical

Grammar:

arr.every( predicate [, thisArg ] )

Type declaration:

interface Array<T> {
  every<S extends T>(
    predicate: (value: T, index: number, array: T[]) => value is S,
    thisArg?: any
  ): this is S[];


  every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
}

Parameter Description:

parametersclarificationtypology
predicateCallback functions for determining array membersfunction
thisArgExecute the callback function’sthis (be) worth

callback function’s arguments:

  • currentValue: the element currently being processed in the array
  • index: index of the current element in the array being processed
  • array: Array of called

Return Value:

Returns when all the array elements satisfy the callback function’s judgment.trueOtherwise, returnfalse。

Methodological note

  • Execution of this method will perform a callback function for each member of the array, the callback function needs to pass the judgment of the code block, the return Boolean value as a member of the test whether the credentials, if it passes the next array member to perform the callback function, until it encounters the first judgment for thefalse immediately gives the instance method a return offalse, otherwise all members pass the callback function of the test, returntrue。
  • The callback function will only be called for indexes that have been assigned values, not for indexes that have been deleted or never assigned values.
  • If you provide an instance method with athisArg parameter to the callback function, thethis value. If this parameter is omitted, it is the value of the callback function when it is called with thethis value, which is a global object in non-strict mode, and passed in strict mode to theundefined。
  • The range of array members to be traversed is determined before the first call to the callback function. The range of the array members to be traversed is determined before the call to theevery() Members added to the array afterward are not accessed by the callback function. If members present in the array are changed, they are passed to the callback function with the value ofevery() access to their values at that moment. Those members that are deleted or not assigned a value will not be accessed.

code example

The following example tests to see if all the elements in the array are greater than 10.

const isBigEnough = (element, index, array) =>
  (element >= 10)[(12, 5, 8, 130, 44)].every(isBigEnough)[
    // false


    (12, 54, 18, 130, 44)
  ].every(isBigEnough);
// true

Array.prototype.filter()

Array.prototype.filter() method creates a new array containing all the elements of the test implemented through the provided function.

grammatical

Grammar:

arr.filter( callback = function (currentValue, index, arr) {} [, thisArg ] )

Type declaration:

interface Array<T> {
  filter<S extends T>(
    predicate: (value: T, index: number, array: T[]) => value is S,
    thisArg?: any
  ): S[];


  filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];
}

Parameter Description:

parametersclarificationtypology
callbackCallback functions for determining array membersfunction
thisArgExecute the callback function’sthis (be) worth

callback function’s arguments:

  • currentValue: the element currently being processed in the array
  • index: index of the current element in the array being processed
  • array: Array of called

Return Value:

Returns an array of a new collection of members that passed the test.

Methodological note

  • This method calls the callback function once for each member of the array and utilizes all the callback functions that make the callback function return thetrue or Equivalenttrue value of the member to create a new array. The callback function will only be called on indexes that have already been assigned values, it will not be called on indexes that have been deleted or never assigned values. Elements that do not pass the callback function test are skipped and are not included in the new array.
  • If providedthisArg parameter, then it will be used as the callback function when it is called with thethis value. Otherwise, the callback function’sthis values will be global objects in non-strict mode and strict mode asundefined。
  • The range of elements to be traversed is determined before the first call to the callback function. Elements that are added to the array after the method is called are not traversed. If already existing elements are changed, the values they pass into the callback function are the values at the moment they are traversed. Elements that are deleted or never assigned a value are not traversed.

code example

basic usage

const isBigEnough = (value) => value >= (10)[(12, 5, 8, 130, 44)].filter(isBigEnough);
// false

Array.prototype.find()

Array.prototype.find() method returns the first member of the array that satisfies the provided determination function.

grammatical

Grammar:

arr.find( callback [, thisArg ] )

Type declaration:

interface Array<T> {
  find<S extends T>(
    predicate: (this: void, value: T, index: number, obj: T[]) => value is S,
    thisArg?: any
  ): S | undefined;
  find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;
}

Parameter Description:

parametersclarificationtypology
callbackCallback functions for determining array membersfunction
thisArgExecute the callback function’sthis (be) worth

callback function’s arguments:

  • currentValue: the element currently being processed in the array
  • index: index of the current element in the array being processed
  • array: Array of called

Return Value:

When the traversed array member passes the callback function’s determination, the member of the array is returned; otherwise, it returnsundefined。

code example

Finding objects in an array using their properties

let foo = [
  { name: 'a', quantity: 2 },
  { name: 'b', quantity: 0 },
  { name: 'c', quantity: 5 },
];


const getFoo = (key) => (arr) => arr.name === key;


console.log(foo.find(getFoo('c')));
// { name: 'c', quantity: 5 }

Array.prototype.findIndex()

findIndex()method returns the array that satisfies the provided test function’sfirst elementtheindexing. Otherwise returns -1.

grammatical

Grammar:

arr.findIndex( callback [, thisArg ])

Type declaration:

interface Array<T> {
  findIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number;
}

Parameter Description:

parameterstypologyclarification
callbackCallback functions for determining array membersfunction
thisArgExecute the callback function’sthis (be) worth

callback function’s arguments:

  • currentValue: the element currently being processed in the array
  • index: index of the current element in the array being processed
  • array: Array of called

code example

basic usage

const arr = [1, 2, 3, 4, 5, 12, 22, 2, 2, 2];


const foo = arr.findIndex(function (currentValue, index, array) {
  return currentValue === 2;
});


console.log(foo);
// 1

Array.prototype.forEach()

Array.prototype.forEach() method is used to iterate over each member of the array.

grammatical

Grammar:

arr.forEach( callbackfn [, thisArg ] )

Type declaration:

interface Array<T> {
  forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
}

Parameter Description:

parametersclarificationtypology
callbackfnCallback function to be executed when iterating over array membersfunction
thisArgExecute the callback function’sthis (be) worth

callbackfn function’s arguments:

  • currentValue: the element currently being processed in the array
  • index: index of the current element in the array being processed
  • array: Array of called

Return Value:

come (or go) backundefined。

Methodological note

  • This method performs a callback function for each item in the array containing a valid value in ascending order, those that have been deleted (using thedelete methods, etc.) or uninitialized items will be skipped (but not those with values ofundefined (e.g. in sparse arrays).
  • The range traversed by this method is determined before the first call to the callback function. The scope of the callback function is determined before the first call to theforEach() Items added to the array after this will not be recognized by thecallbackfn Accessed. If an already existing value is changed, the value passed to thecallbackfn The value offorEach Iterate to their values at that moment. Deleted items are not iterated over. If visited elements are deleted during iteration (e.g., using theshift() ) , after which the elements will be skipped.
  • forEach() For each array element, perform thecallbackfn function; unlike themap() orreduce() It always returnsundefined values and may not be chained. A typical use case is to perform a side effect at the end of a chain.

attention (heed): No way to abort or jump outforEach loop, except for throwing an exception. If you need this, use theforEach() function is wrong, you can use a simple loop as an alternative. If you are testing an array of elements to see if they match a condition and need to return a boolean value, use theevery() maybesome(). If available, the new methodfind() orfindIndex() It can also be used for early termination of truth tests.

code example

const arr = ['a', 'b', 'c'];


arr.forEach(function (element) {
  console.log(element);
});


arr.forEach((element) => console.log(element));
// a b c

Array.prototype.map()

Array.prototype.map() Updates each value in the given array according to the passed conversion function and returns a new array of the same length. It accepts a callback function as an argument to perform the conversion process.

grammatical

Grammar:

const new_arr = old_arr.map(callback = function(currentValue, index, array){} [, thisArg])

Type declaration:

interface Array<T> {
  map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
}

Parameter Description:

parametersclarificationtypology
callbackFuncCallback function to be executed when iterating over array membersfunction
thisArgExecute the callback function’sthis (be) worth

callback function’s arguments:

  • currentValue: the element currently being processed in the array
  • index: index of the current element in the array being processed
  • array: Array of called

Return Value:

Returns the result of the callback function, or the currently traversed array member if no return value is set.

Methodological note

  • This method performs a callback function for each item in the array containing a valid value in ascending order, those that have been deleted (using thedelete methods, etc.) or uninitialized items will be skipped (but not those with values ofundefined (e.g. in sparse arrays).
  • utilizationmap method handles arrays, the range of the array elements in thecallback method is determined before the method is called for the first time. In themap method is executed: newly added elements in the original array will not becallback accessed; if already existing elements are changed or deleted, their pass-through to thecallback The value ofmap method traverses to their values at that moment; and the deleted elements will not be accessed.

code example

The following code creates a new array with a value that is the square root of the corresponding number in the original array.

const numbers = [1, 4, 9];
const roots = numbers.map(Math.sqrt);


// Math.sqrt(x)


console.log(numbers);
// [1, 4, 9]
console.log(roots);
// [1, 2, 3],

Array.prototype.push()

Array.prototype.push() method is used to add one or more elements to the end of the current array and return the new array length.

grammatical

Grammar:

arr.push( item1 [, items...] )

Type declaration:

interface Array<T> {
  push(...items: T[]): number;
}

Parameter Description:

parametersclarificationtypology
item1Adding Elementsany
itemNOther elements addedany

If the added element is of array type, it will still be treated as one element, just that the element is of array type. To merge two arrays, use theconcat() function.

Return Value:

Returns the length of the array after adding elements.

Methodological note

When adding a new element to an array, the array’slength properties will change as well. In general, the array’slength Attributes will be addedN ( N (for the number of elements added).

push() The method is intentionally generalizable. The methodology andcall() maybeapply() When used together, they can be applied to array-like objects.push() method determines where to start inserting the given value based on the length attribute. If thelength cannot be converted to a numeric value, then the inserted element is indexed 0, including thelength When not present. When thelength When it does not exist, it will be created.

code example

basic usage

const foo = ['a', 'b'];
const bar = foo.push('c', 'd');


console.log(foo);
// ['a', 'b', 'c', 'd']


console.log(bar);
// 4

Array.prototype.pop()

Array.prototype.pop() method is used to remove the last member of an array and return that array member.

grammatical

Grammar:

arr.pop();

Type declaration:

interface Array<T> {
  pop(): T | undefined;
}

Return Value:

Returns the array member that was removed. If the array is empty (doesn’t have any elements), then return theundefined。

Methodological note

  • The method andcall() maybeapply() When used together, they can be applied to class array objects.pop The methodology is based onlength attribute to determine the position of the last element. If it does not contain thelength attribute orlength attribute cannot be converted to a numeric value, and will convert thelength is set to 0 and returnsundefined。
  • Since this method removes the array ofThe last elementof an arraylength attribute will also change (if there are elements in the array), and in general, the array’slength The attribute will be reduced by 1.
  • If you’re callingpop()It returnsundefined。

code example

basic usage

let foo = ['a', 'b', 'c', 'd'];


let popped = foo.pop();


console.log(foo);
// ['a', 'b', 'c', 'd']


console.log(popped);
// 'd'

Array.prototype.sort()

Array.prototype.sort() method is used to sort the members of an array object in the specified order and return the sorted array.

grammatical

Grammar:

arr.sort(compareFn);

Type declaration:

interface Array<T> {
  sort(compareFn?: (a: T, b: T) => number): this;
}

Parameter Description:

parametersclarificationtypology
compareFn(Optional) Name of the function that specifies how to compare the order of the elementsfunction

Return Value:

Returns the sorted array object.

In the sorting process, does not create a new array object, the returned array object is the current array itself after sorting.

Methodological note

If omittedcompareFn parameter, the elements will be in ASCII character order of theascending orderMake an arrangement.ASCII character table

If providedcompareFn parameter, then the function must return one of the following values:

  • Returns a negative value if the first parameter passed is smaller than the second.
  • Returns zero if the two arguments are equal.
  • Returns a positive value if the first argument is greater than the second.

The format of the comparison function is as follows:

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  return 0;
}

code example

basic usage

const foo = ['b', 'c', 'a'];


fruit.sort();
// ['a', 'b', 'c']
const bar = [1, 10, 21, 2];


bar.sort();
// [1, 10, 2, 21]

Note that 10 comes before 2, because in Unicode pointer order"10" exist"2" Before.

const baz = ['word', 'Word', '1 Word', '2 Words'];


baz.sort();
// ['1 Word', '2 Words', 'Word', 'word']

In Unicode, numbers come before uppercase letters and uppercase letters come before lowercase letters.

summarize

In this blog, we explore together theJavaScript built-in objects, for example:Object, Array, Global Object, String and FuntionJavaScript is a very powerful and widely used programming language. By mastering the basic syntax and concepts, you have the foundation to get started with JavaScript programming. In the future, you’ll be able to create more interactive web pages, implement more stunning dynamic effects, and even build your own web applications. But this is just the beginning; there are many more in-depth topics waiting for you to explore.
We’ll follow up this front-end column withES6, garbage collection, js algorithm skills, Vue introductory practice, React practice, front-end interview questionsetc. If you are interested, please feel free toThree likes and a follow.I, as well as my front-end column, will see you in the next article.