Built in objects for JavaScript

Posted by Res on Fri, 21 Jan 2022 15:38:11 +0100

 

catalogue

1, Number

1. isFinite()

2. isInteger()

3. isNaN()

4. parseFloat()

5. parseInt()

2, String

1. indexOf()

2. replace()

3. search()

4. concat()

5. split()

6. slice()

7. substr()

8. substring()

9. includes()

3, Array

1. join()

2. push()

3. pop()

4. shift()

5. reverse()

6. filter()

7. forEach()

8. find()

4, Object

1. Object.keys(obj)

2. Object.getOwnPropertyNames(obj)

3. Object.defineProperty(obj,prop,descriptor)

Today, I'd like to share with you a wave of built-in objects in JavaScript and common object methods (ง) ˙ o ˙) ว 

Everything in JavaScript is an Object: Number, String, Array, Object, Function, and so on

Where Object is the parent of all objects

In JavaScript, an object is data that has properties and methods

When I first came into contact with objects, I didn't learn very well. At that time, I felt that objects were so complex that I couldn't remember several methods of defining objects and the use of objects. I basically relied on rote. Sure enough, I forgot everything when I used it again. However, objects and array objects are two very common ways to store data. Even if you don't know how to do it at the beginning, don't worry. Practice makes perfect when you use more later. Below, I summarize some common methods of object.

1, Number

methoddescribe
isFinite()Judge whether a finite number
isInteger()Determine whether an integer
isNaN()Determine whether a NaN
parseFloat()Resolves a value to a floating point number
parseInt()Resolves a value to an integer

1. isFinite()

Syntax: number isFinite(value)

Return value: true or false

Number.isFinite(Infinity)    // false
Number.isFinite(NaN)         // false
Number.isFinite(-Infinity)   // false


Number.isFinite(0)           // true
Number.isFinite('123')       // false

2. isInteger()

Syntax: number isInteger(value)

Return value: true or false

Number.isInteger(0)          // true
Number.isInteger(-1)         // false

Number.isInteger(0.01)       // false
Number.isInteger(Infinity)   // false
Number.isInteger(NaN)        // false
Number.isInteger(undefined)  // false

3. isNaN()

Syntax: number isNaN(value)

Return value: true or false

Number.isNaN(NaN)            // true
Number.isNaN(Number.NaN)     // true
Number.isNaN(0 / 0)          // true

//The following will return true if global isNaN() is used
Number.isNaN("NaN")          // false, the string "NaN" will not be implicitly converted to the number NaN
Number.isNaN(undefined)      // false
Number.isNaN({})             // false
Number.isNaN("blabla")       // false

//false is returned below
Number.isNaN(true)
Number.isNaN(null)
Number.isNaN(37)
Number.isNaN("37.37")
Number.isNaN("")

4. parseFloat()

Function:

  • Resolves the value to a floating point number
  • Positive sign (+), negative sign (-), number (0-9), decimal point (.) Or a character other than exponent (e or E) in scientific notation, it will ignore this character and all subsequent characters and return the floating-point number that has been parsed at present
  • The appearance of the second decimal point will also stop parsing (all characters before this will be parsed)
  • Whitespace characters in the first and last bits of the parameter are ignored
  • NaN is returned if the first character of the parameter string cannot be parsed into a number
  • parseFloat can also parse and return Infinity
  • parseFloat parses BigInt as Numbers, losing precision. Because the last n character is discarded

Syntax: number parseFloat(string)

Return value: floating point number or NaN

// The following examples return 3.14
Number.parseFloat(3.14)
Number.parseFloat('3.14')
Number.parseFloat('  3.14  ')
Number.parseFloat('3.14.15')
Number.parseFloat('314e-2')
Number.parseFloat('0.0314E+2')
Number.parseFloat('3.14todo')
Number.parseFloat({ toString: function() {return "3.14" } })

// The following example returns NaN
parseFloat("ABCD233")

5. parseInt()

Syntax: number parseInt(string[,radix])

Parameters:

  • String: the value to parse. If this parameter is not a string, it is converted to a string using the ToString abstract operation. Ignore leading spaces in this parameter
  • Radius: an integer between 2 and 36, representing the cardinality of the string

1) if the input string starts with "0x" or "0x" (a 0 followed by a lowercase or uppercase X), then the radius is assumed to be 16 and the rest of the string is parsed into hexadecimal numbers

2) if the input string starts with "0" (0), the radix is assumed to be 8 (octal) or 10 (decimal). Which radio to choose depends on the implementation. ECMAScript 5 clarifies that 10 (decimal) should be used, but not all browsers support it. Therefore, when using parseInt, be sure to specify a radius

3) if the input string starts with any other value, the radix is 10 (decimal)

Return value: integer or NaN

//The following examples return 15
parseInt("0xF",16)
parseInt("F",16)
parseInt("17",8)
parseInt("015",10)     // parseInt(015,10) returns 13
parseInt(15.99,10)
parseInt("FXX123",16)
parseInt("15 * 3",10)
parseInt("15e2",10)
parseInt("15px",10)
parseInt("12",13)

//The following examples return - 15
parseInt("-F",16)
parseInt(-15.1,10)
parseInt("-15e1",10)

//The following examples return NaN
parseInt("Hello",8)    // It's not a value at all
parseInt("456",2)      // No number other than '0, 1' is a valid binary number

2, String

methoddescribe
indexOf()Returns the position where the matching string first appears. If it does not exist, it returns - 1
concat()Connect multiple strings and return the connected string
localeCompare()Comparing two strings, the same returns 0 and the different returns - 1
includes()Judge whether there is a specific string in the string, return true if any, and return false if none
replace()Replaces the regular matching string with the specified string, and returns the replaced string
search()Returns the index of a regular matching string
slice()Returns a string at a specified location
splite()Returns an array of strings separated by regular matching. The length of the array can be specified
substr()Returns the characters in a string starting at a specified position
substring()Returns the character between two subscripts specified in a string
toString()Returns a string representing the object
valueOf()Returns the original value of the specified object

1. indexOf()

Function:

  • Find the index in str from left to right for the first time according to the first parameter. If yes, the index is returned, and - 1 is not returned
  • When null value is passed, if there is a second parameter, the second parameter is returned, and 0 is not returned
  • Case sensitive

Syntax: str.indexOf(searchValue [, fromIndex])

Parameter: Return - 1 if there is no parameter

  • searchValue: destination string
  • fromIndex: the index of the starting position of the search, optional, ranging from 0 to str.length - 1. Press 0 to start searching without transmitting this parameter
var str = 'The moonlight is so beautiful tonight nice'
str.indexOf() // -1
str.indexOf('') // 0
str.indexOf('of') // 2
str.indexOf('of',5) // -1
str.indexOf('nice',5) // 6
str.indexOf('Nice') // -1 

2. replace()

Function: replace some characters in str with some characters, or replace a substring that matches the regular expression

Syntax: str.replace(regexp | substr,newSubStr | function)

Parameter: if the second parameter is not passed, it will be replaced with undefined

  • regexp(pattern): a RegExp object or its literal. The matching content of the rule will be replaced by the return value of the second parameter
  • substr(pattern): a string to be replaced by newSubStr. It is treated as an entire string rather than a regular expression. Only the first match is replaced
  • New substr (replacement): a string used to replace the matching part of the first parameter in the original string. Some special variable names can be interpolated into the string
  • function(replacement): a function used to create a new substring. The return value of the function will replace the result matched by the first parameter

Return value: a new string after replacement without modifying the original string

var str = 'I'm going to rest tonight'

var reg = /today/gi
str.replace(reg,'tomorrow') // 'rest tomorrow night '

function reStr(){ return 'sleep'}
str.replace(reg,reStr) // 'going to bed tonight'

str.replace('night') // 'undefined to rest today'

3. search()

Function: find the incoming string or regular matching character in str, find the return index, and return - 1 if not found

Syntax: str.search(regexp/substr)

Parameter: regexp/substr, which specifies the substring or RegExp object to match

Return value: the first match in the original string to the starting position of the target string

The search() method does not perform a global match, it ignores the flag g. That is, it matches only once. If no match is found, - 1 is returned

var str = 'The moonlight is so beautiful tonight'
str.search() // 0
str.search('') // 0
str.search('moonlight') // 3
str.search('nice') // -1

4. concat()

Function: used to connect two or more strings

Syntax: str.concat(string2, string3 [,..., stringN])

Parameter: string2 Stringn, multiple strings connected with the original str

Return value: a new string after connection without changing the original str

The concat method does not modify the original string

var item1 = 'Tonight?'
var item2 = 'moonlight'
var item3 = 'beautiful'
item1.concat(item2,item3) // 'the moon is beautiful tonight '

5. split()

Function: use the specified string to divide the original str into a string array, similar to array Inverse operation of join()

Syntax: str.split([separator [, limit]])

Parameters:

  • separator: a string or regular expression that splits the original str from the place specified by this parameter
  • Limit: limit the maximum length of the returned array

Return value: an array of strings

var str = 'Today is Thursday, tomorrow is Friday'
str.split('') // ["today", "sky", "Star", "period", "four", "bright", "sky", "Star", "period", "Five"]
str.split('',1) // [today]
str.split('day') // [today, Thursday, tomorrow, Friday]

6. slice()

Function: intercept a part of the string specified in str and return this part of the string, which is the same as array Slice() similar

Syntax: str.slice(beginIndex [, endIndex])

Parameters:

  • beginIndex: the intercepted starting index. If it is not transmitted, it starts from 0 by default. If it is transmitted as a negative number, it starts from str.length + beginIndex (i.e. from the last beginIndex)
  • endIndex: the end index of the interception. If it is not transferred, the default is str.length. If it is transferred to a negative number, it starts from str.length + endIndex

Return value: intercept part, a new string, and the original str does not change

var str = 'Today is Thursday, tomorrow is Friday'
str.slice() // 'today Thursday, tomorrow Friday '
str.slice(2) // 'thursday, tomorrow, Friday '
str.slice(2,3) // 'star '
str.slice(6) // 'tomorrow Friday '
str.slice(-5) // 'tomorrow Friday '
str.slice(-5,str.length-2) // 'tomorrow star '
str.slice(-5,-1) // 'tomorrow week '

7. substr()

Function: intercept a part of the string specified in str and return this part of the string

Syntax: str.substr(beginIndex [, length])

Parameters:

  • beginIndex: the intercepted starting index. If it is not passed, the default value is 0. If it is passed negative, it starts from str.length + beginIndex (i.e. from the last beginIndex)
  • Length: the length of the intercepted string. If it is not specified, it will be intercepted to the end of str by default

Return value: intercept part, a new string, and the original str does not change

Note: non ECMAscript is standardized and may be removed in the future. It is not recommended

var str = 'the weather is nice today!'
str.substr() // 'the weather is fine today! '
str.substr(2) // 'the weather is fine! '
str.substr(2,3) // 'the weather '
str.substr(6) // '!'
str.substr(-6,str.length-2) // '!'
str.substr(-6,-1) // '' 

8. substring()

Function: intercept the characters between two specified subscripts in the string (similar to slice, but the parameter does not accept negative values)

Syntax: str.substring(beginIndex [, endIndex])

Parameters:

  • beginIndex: the intercepted starting index. If it is not transferred, it is 0 by default. If it is transferred to a negative value, it is 0 by default
  • endIndex: optional. If it is not specified, it will be intercepted to the end of the original string by default

Return value: intercept part, a new string, and the original str does not change

Note: when both parameters are non negative numbers, if the value of beginIndex is greater than that of endIndex, beginIndex and endIndex will be exchanged

var str = 'the weather is nice today!'
str.substring() // 'the weather is fine today! '
str.substring(2) // 'the weather is fine! '
str.substring(2,3) // 'days'
str.substring(3,2) // 'days'
str.substring(6) // '!'
str.substring(-6,-1) // ''
str.substring(-6) // 'the weather is fine today! '
str.substring(-6,str.length-3) // 'weather today'

9. includes()

Function: judge whether there is a specified string in str

Syntax: str.includes(searchString [, position])

Parameters:

  • searchString: the string to find in str
  • position: optional. The default value is 0, and the negative value is 0

Return value: if there is a specified string in str, it returns true, but not false

var str = 'The moon is beautiful tonight'
str.includes('tomorrow') // false
str.includes('Tonight?') // true
str.includes('beautiful',9) // false
str.includes('Tonight?',-666) // true

3, Array

methoddescribe
filter()The elements in the original array can be returned through the filter to form a new array
forEach()Call a function to process each element in the array
join()Connect all the elements in the array and return a string
pop()Returns the last element in the array and deletes it
push()Adds an element to the end of the array and returns the length of the new array
reverse()Reverse the order of array elements -- first becomes last, and last becomes first
shift()Deletes the first element of the array and returns
find()Returns the value of the first element in the array that satisfies the provided test function. Otherwise, undefined is returned

1. join()

Function:

  • Put all the elements in the array into a string, and the elements are divided by the specified separator
  • If separator parameter is omitted, comma is used as separator
  • If the array has only one item, the item is returned without the delimiter
  • Do not change the original array

Syntax: arr.join(separator)

Parameter: separator (optional. Specifies the separator to use. If this parameter is omitted, a comma is used as the separator)

// arr.join() does not pass parameters, and is separated by "," by default
var arr = new Array(3)
arr[0] = "you"
arr[1] = "good"
arr[2] = "ah"
var nArr = arr.join()
console.log(nArr)  // You, okay, yeah

// arr.join() passes parameter "-", separated by "-"
var arr2 = new Array(3)
arr[0] = "you"
arr[1] = "good"
arr[2] = "ah"
var nArr2 = arr2.join()
console.log(nArr2)  // You. - okay. - yeah

2. push()

Function:

  • Adds one or more elements to the end of the array and returns the new array length
  • Change original array

Syntax: arr.push(element,..., elementN)

Parameter: elementn (element added to the end of the array)

var arr = [1,2,3]
var len = arr.push('a','b','c')
console.log(arr) // [1,2,3,"a","b","c"]
console.log(len) // 6 (the new length of the returned array is 6)


// Merge multiple arrays
var arr = [1,2,3]
var arr2 = ['a','b','c']
var arr3 = ['d','e','f']
arr.push(...arr2,...arr3)
console.log(arr) // [1,2,3,"a","b","c","d","e","f"]

3. pop()

Function:

  • Used to delete the last element of the array, reduce the length of the array by 1, and return the deleted element
  • If the array is already empty, pop() does not change the array and returns undefined
  • Change original array

Syntax: arr.pop()

var arr = [1,2,3]
var getLast = arr.pop() // First arr.pop()
console.log(arr) // [1,2]
console.log(getLast) // 3 (after executing arr.pop(), return the last element of the array)

4. shift()

Function:

  • Used to delete the first element of the array from it and return the removed element
  • If the array is empty, the shift() method does nothing and returns undefined
  • This method is to modify the original array directly

Syntax: arr.shift()

var arr = [1,2,3]
var getFirst = arr.shift();
console.log(arr) // [2,3]
console.log(getFirst) // 1 (execute arr.shift() to return the first element of the array)

5. reverse()

Function:

  • Used to reverse the order of elements in an array
  • This method will directly modify the original array without creating a new array

Syntax: arr.reverse()

var arr = [1,2,3,4,5]
var reArr = arr.reverse()

console.log(reArr) // [5,4,3,2,1]
console.log(arr) // [5,4,3,2,1] the original array is changed

6. filter()

Function:

  • Call the callback function once for each element in the array and create a new array with all the value elements that make the callback return true or equivalent to true
  • The traversed element range is determined before the first call to callback. Elements added to the array after calling the filter will not be traversed by the filter. If the existing elements are changed, the value they pass in the callback is the value at the moment when the filter traverses them. Elements that are deleted or never assigned will not be traversed.
  • Returns a new array of elements that passed the test. If none of the array elements passed the test, an empty array is returned
  • It does not change the original array, it returns the filtered new array

Syntax: VAR newarray = array. Filter (callback (element [, index [, array]]] [, thisArg])

Parameters:

  • callback: a function used to test each element of an array. Returning true means that the element passes the test, and the element is retained. If false, it is not retained. It accepts the following three parameters:

Element: the element currently being processed in the array

Index (optional): the index of the element being processed in the array

Array (optional): the array itself that called the filter

  • Thisarg (optional):

The value used for this when callback is executed

//Search the array for matching entries
var fruits = ['apple','banana','grapes','mango','orange']

function filterItems(query){
   return fruits.filter(function(el){
        return el.toLowerCase().indexOf(query.toLowerCase()) > -1   
   })
}

console.log(filterItems('ap')) // ['apple','grapes']
console.log(filterItems('an')) // ['banana','mango','orange']

7. forEach()

Function:

  • Method executes the callback function once in ascending order for each item in the array that contains valid values
  • If the thisArg parameter has a value, this will point to the thisArg parameter every time the callback function is called. If the thisArg parameter is omitted or its value is null or undefined, this points to the global object
  • If an arrow function expression is used to pass in a function parameter, the thisArg parameter is ignored because the arrow function is lexically bound to the this value
  • There is no way to abort or jump out of a forEach() loop except by throwing an exception. If you need to abort or jump out of a loop, the forEach() method is not the tool you should use
  • There is no return value, just call func for each element
  • The original array will not be changed

Syntax: arr.forEach(callback(currentValue [, index [, array]]] [, thisArg])

Parameters:

  • callback: a function used to test each element. It accepts three parameters:

currentValue: the element being processed in the array

Index (optional): the index value of the element being processed in the array

Array (optional): an array that calls forEach()

  • Thisarg (optional):

The value of this used when executing callback

// Do nothing with uninitialized values (sparse array)
var arr = [1,{},3,null,5,,7]
arr.forEach(function(v,i,a){
  console.log("Processing section" + i + "Elements:" + v)
})

// Processing element 0: 1
// Processing the first element: [object]
// Processing element 2: 3 
// Processing element 3: null
// Processing element 4: 5
// Processing element 6: 7
// The fifth element was skipped because it was not initialized

8. find()

Function:

  • Returns the value of the first element in the array that satisfies the provided test function. Otherwise, undefined is returned
  • The find method executes the callback function once for each element in the array until one callback returns true. When such an element is found, the method will immediately return the value of the element, otherwise it will return undefined
  • The callback function will be called for each index in the array, that is, from 0 to length - 1, not just those assigned indexes, which means that for sparse arrays, this method is less efficient than those methods that only traverse the indexes with values

Syntax: arr.find(callback [, thisArg])

Parameters:

  • callback: a function executed on each item of the array, which receives three parameters:

Element: the element currently traversed

Index (optional): the index currently traversed

Array (optional): array itself

  • Thisarg (optional):

The object used as this when the callback is executed

var arr = [
  {name:'Zhang San',age:20},
  {name:'Li Si',age:16},
  {name:'Wang Wu',age:16},
]

arr.find(function(item){
   return item.age === 16 //Returns the first item with an age of 16
}) // {name: 'Li Si', age: 16}

4, Object

methoddescribe
keys()Gets an array of all enumerable properties on the target object
getOwnPropertyNames(obj)Gets an array of all self owned attribute names (including non enumerable attributes) on the target object
defineProperty(obj,prop,descriptor)Define a new property on an object or modify an existing property and return the object

1. Object.keys(obj)

Function: get an array of all enumerable attributes on the target object

Parameters:

  • Obj (required): target object
var person = {
    type:'person',
    say:function(){}
  };
  //Create obj object based on person object
  var obj = Object.create(person,{
    sex:{
      writable: true,
      configurable: true,
      enumerable: false, //Set the sex property to enumerable
      value: 'm'
    },
    age:{
      writable: true,
      configurable: true,
      enumerable: true, //Set the age property to enumerable
      value: 23
    }
  });

  obj.name = '123'; //The custom attribute name is enumerable by default
  console.log(obj.propertyIsEnumerable('name')); //true, successfully verify that the name attribute is enumerable

  //Use for in to obtain all enumerable attributes on obj (including those on its own and prototype chain)
  var arr = [];
  for(var key in obj){
    arr.push(key);
  }
  console.log(arr); //["age", "name", "type", "say"]

  //Use object Keys() can obtain all enumerable self attributes on obj
  console.log(Object.keys(obj)); // ["age", "name"]

2. Object.getOwnPropertyNames(obj)

Function: get the array composed of all self owned attribute names (including non enumerable attributes) on the target object

Parameters:

  • Obj (required): target object
var obj = {};
obj.say = function(){};

Object.defineProperties(obj,{
    name:{
      writable: true,
      configurable: true,
      enumerable: true,
      value: 'gwg'
    },
    age:{
      writable: true,
      configurable: true,
      enumerable: false,
      value: 23
    }
});

var arr = Object.getOwnPropertyNames(obj);
console.log(arr); //["say", "name", "age"]

3. Object.defineProperty(obj,prop,descriptor)

Function: define a new property on an object or modify an existing property and return the object

Parameters:

  • Obj (required): the target object to be manipulated
  • Prop (required): target attribute defined or modified
  • Descriptor (required): the descriptor of the attribute

descriptor parameter:

  • Data properties

Value: value (default: undefined)

writable: whether the value of the attribute can be modified (false by default)

configurable: whether attributes can be deleted and redefined through delete (false by default)

enumerable: whether to enumerate for in (false by default)

  • Access properties

get(): access (undefined by default)

set(): set (default: undefined)

var obj = {};
Object.defineProperty(obj,'name',{
    writable: true,
    configurable: true,
    enumerable: false,
    value: 'Zhang San'
});

console.log(obj.name); //'Zhang San'
for(var key in obj){
    console.log(obj[key]); //No result
}

be careful:

var obj = {};

obj.item = 1;
// Equivalent to:
Object.defineProperty(obj, "item", {
  value: 1,
  writable: true,
  configurable: true,
  enumerable: true
});


// In addition,
Object.defineProperty(obj, "item", { value : 1 });
// Equivalent to:
Object.defineProperty(obj, "item", {
  value: 1,
  writable: false,
  configurable: false,
  enumerable: false
});

Custom getter s and setter s:

function CustomizeObject() {
    var attr = null;
    var saveArr = [];

    Object.defineProperty(this, 'attr', {
        get: function() {
            console.log('get attr');
            return attr;
        },
        set: function(value) {
            attr = value;
            saveArr.push({ val: attr });
        }
    });

    this.getSaveArr = function() { return saveArr; };
}
  
var obj = new CustomizeObject();
obj.attr; // 'get attr'
obj.attr = 11;
obj.attr = [1,2,3,4];
obj.getSaveArr(); // [{val: 11},{val:[1, 2, 3, 4]}]

over~!

Topics: Javascript Front-end html5