JS built-in objects and extension libraries

Table of contents

1. Built-in objects and built-in functions

basic packaging type

boolean type

String type

NumberType

Math object

Date object

2. Extended library

1.Moment.js

2.lodash

1. Built-in objects and built-in functions

There are three types of objects in JavaScript: custom objects, built-in objects, and browser objects. 

Built-in objects : some objects that come with the js language, these objects are for developers to use, and provide some commonly used or the most basic and necessary functions (properties and methods).

Built-in objects commonly used in JS : Array, Boolean, Date, Math, Number, String, Error, Function, Global, Object, RegExp

Built-in function : A function embedded in the calling function is called a built-in function, also known as an inline function. It is used to improve the execution efficiency of the program. It greatly improves the efficiency of programmers and the reading of programs. JS built-in functions do not belong to any object, and these functions can be used anywhere in the JS statement.

basic packaging type

The classification of data is divided into basic data types and reference types. Reference types have their own built-in methods, and you can also customize other methods to manipulate data, while basic data types cannot. According to the latest ES standard definition, the basic data types (primitive value) include Undefined, Null, Boolean, Number, Symbol, String. In order to facilitate the operation of basic type values, ECMAScript provides 3 special reference types ( basic packaging types ): Boolean, Number, String. Primitive wrapper types, like reference types, have built-in methods to perform additional operations on the data.

boolean type

The Boolean type has no specific properties or methods. Generally, Boolean is used directly as a tool method.

String type

object properties

Attributes describe
constructor a reference to the function that created the object
length the length of the string
prototype Allows you to add properties and methods to objects

String also contains common methods for objects, such as valueOf(), toLocaleString(), and toString() methods, but these methods all return the basic value of the string.

character method

method describe
charAt(index) Returns the character at the specified index position
charCodeAt(index) Returns the character at the specified index position in Unicode encoding

 String manipulation methods

method describe
concat() connection string.
slice() method to extract a portion of a string and return the extracted portion as a new string.
substring() Extracts the characters in a string between two specified index numbers.
substr() Extracts the specified number of characters in a string from the starting index number.

 String position method

method describe
indexOf(str,n) Search for the first str from n, and return the searched index value
lastIndexOf(str,n) The last str to search from n, and return the searched index value

 Case conversion method

method describe
toLowerCase() Convert a string to lowercase.
toUpperCase() Convert a string to uppercase.
toLocaleLowerCase() Convert a string to lowercase. localization
toLocaleUpperCase() Convert a string to uppercase. localization

String pattern matching method

method describe
match() Find a match for one or more regular expressions.
replace() Replace substrings that match the regular expression.
search() Retrieves values ​​that match the regular expression.
split() Split a string into an array of strings.

usage:

//charAt(index)   返回指定索引位置的字符。index必须
var str = 'hello';
console.log(str.charAt(0)); // h
//charCodeAt(index)以Unicode编码形式返回指定索引位置的字符
var str = 'hello';
console.log(str.charCodeAt(0)); // 104
//substring(start,end)  提取字符串中两个指定的索引号之间的字符。
var str = 'hello';
console.log(str.substring(0, 3)); // hel
console.log(str.substring(0)); // hello
//substr(start,length)  从起始索引号提取字符串中指定数目的字符
var str = 'hello';
console.log(str.substr(0, 3)); // hel
//大小写转换方式
var str = 'hello world';
// 转换为大写
console.log(str.toUpperCase()); //HELLO WORLD
// 转换为小写
console.log(str.toLowerCase()); //hello world
//字符串的模式匹配方法
var str = 'HELLO World';
console.log(str.match('L'));//找到 L,返回 L 否则返回 null
console.log(str.search('L'));//找到 L 的位置,和 indexOf 类似
console.log(str.replace('L', 'Q'));//把 L 替换成 Q
//如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。
console.log(str.split(''));//把字符串分割为字符串数组。

NumberType

Built-in properties (static properties, just call them directly)

Attributes describe
MAX_VALUE The largest number that can be represented.
MIN_VALUE The smallest number that can be represented.
NaN non-numeric value.
NEGATIVE_INFINITY Negative infinity, which is returned on overflow.
POSITIVE_INFINITY Positive infinity, which is returned on overflow.
prototype Enables you to add properties and methods to objects.

built-in methods (object methods)

method describe
Converts a number to a string, using the specified radix.
Converts a number to a string, using the native number format order.
toFixed Converts a number to a string with the specified number of digits after the decimal point.
toExponential Converts the value of an object to exponential notation.
toPrecision 方法可在对象的值超出指定位数时将其转换为指数计数法。
valueOf 返回一个 Number 对象的基本数字值。

 用法案例:

//toString 把数字转换为字符串,使用指定的基数。
var num = 123;
console.log(num.toString()); //123
//toLocaleString 把数字转换为字符串,使用本地数字格式顺序。
var num = 123;
console.log(num.toLocaleString()); //123
//toFixed 把数字转换为字符串,结果的小数点后有指定位数的数字。
var num = 123;
console.log(num.toFixed(2)); // 123.00
//toExponential 把对象的值转换为指数计数法。科学计数法
var num = 123;
console.log(num.toExponential()); // 1.23e+2
//toPrecision 方法可在对象的值超出指定位数时将其转换为指数计数法。
var num = 123;
console.log(num.toPrecision(2)); // 1.2e+2
//valueOf 返回一个 Number 对象的基本数字值。
var num = 123;
console.log(num.valueOf()); // 123 number

Math对象

Math对象主要用于解决数学问题

Math对象区别于其他对象,没有构造函数 Math(),像 Math.sin() 这样的函数只是函数,不是某个对象的方法。通过把 Math 作为对象使用就可以调用其所有属性和方法。

math对象的常用方法

//Math.min() 求一组数中的最小值
console.log(Math.min(2,1,3,4,4)); //1
//Math.max() 求一组数中的最大值
console.log(Math.max(2,1,3,4,4)); //4
//将小数值舍入为整数的几个方法
//Math.ceil() 向上舍入
console.log(Math.ceil(2.1)); //3
//Math.floor() 向下舍入
console.log(Math.floor(2.7)); //2
//Math.round() 四舍五入
console.log(Math.round(2.7)); //3
console.log(Math.round(2.1)); //2
//Math.random() 返回大于0小于1的一个随机数 [0,1)
console.log(Math.random()); // 随机数

Date对象

Date 对象用于处理日期和时间。是JS提供的内置构造函数。

创建Date对象

var myDate = new Date();
console.log(myDate); //2021-08-30T14:27:30.481Z
//在node环境和浏览器环境输出不同

 new Date()可以获取到一个你传递进去的时间

var time = new Date('2020-06-06 06:06:06')
console.log(time) 
// node环境下  2020-06-05T22:06:06.000Z
// 浏览器环境下 Sat Jun 06 2020 06:06:06 GMT+0800 (中国标准时间)

// 第一个参数表示年
// 第二个参数表示月份,月份从0开始计数,0表示1月,11表示12月
// 第三个参数表示该月份的第几天,1~31
// 第四个参数表示当天的几点,0~23
// 第五个参数表示的是该小时的多少分钟,0~59
// 第六个参数表示该分钟的多少秒,0~59
var time = new Date(2020, 00, 1, 10, 10, 10);
console.log(time);
// node环境下  2020-01-01T02:10:10.000Z
// 浏览器环境下 Wed Jan 01 2020 10:10:10 GMT+0800 (中国标准时间)

常用对象方法

var time = new Date();
// 获取当前时间,使用toString()进行转换
console.log(time.toString()); //Mon Aug 30 2021 22:52:12 GMT+0800 (GMT+08:00)
// 获取当前时间 本地化字符串
console.log(time.toLocaleString()); // 2021-8-30 22:52:12

// getFullYear() 得到指定字符串中的哪一年
console.log(time.getFullYear()) // 2021
// getMonth() 得到指定字符串中的哪个月 注意月份是从0开始数的0->1月,1->2月,依此类推
console.log(time.getMonth()) // 7  实际是8月
// getDate() 得到指定字符串中的哪一天
console.log(time.getDate()) // 30
// getHours() 得到指定字符串中的哪小时
console.log(time.getHours()) // 22
// getMinutes() 得到指定字符串中的哪分钟
console.log(time.getMinutes()) // 45
// getSeconds() 得到指定字符串中的哪秒钟
console.log(time.getSeconds()) // 23
// getDay() 得到指定字符串当前日期是周几(周日是0,周六是6)
console.log(time.getDay()) // 1

// getTime() 得到执行时间到 格林威治时间的毫秒数 时间戳
console.log(time.getTime()) // 1630334723399

2、扩展库

1.Moment.js

JavaScript日期处理类库

//Node.js中使用
// 在当前目录下使用node安装moment库
npm install moment --save
// 模块化导入moment
var moment = require('moment');
// 设置本地语言为中文
require('moment/locale/zh-cn')
moment.locale('zh-cn');
// 根据对应的格式输出当前时间
console.log(moment().format('MMMM Do YYYY, h:mm:ss a'));
//八月 30日 2021, 11:07:46 晚上
// 浏览器中使用
// 可以下载js文件,也可使用对应的cdn文件,bootcdn
<script src="moment.js"></script>
<script>
    moment().format();
</script>

时间戳转换

console.log(moment(parseInt(1630334723399)).format('YYYY-MM-DD HH:mm:ss'));// 2021-08-30 22:45:23

有关format的格式参考 http://momentjs.cn/docs/#/displaying/format/

其他方法见Moment.js 中文网

2.lodash

Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。

(1)_.cloneDeep

可用于解决浅拷贝问题

var _ = require('lodash');
var obj = {
  name:'zhangsan',
  age: 18
}
var obj2 = _.cloneDeep(obj);
obj2.age = 20;
console.log(obj); // { name: 'zhangsan', age: 18 }
console.log(obj2); // { name: 'zhangsan', age: 20 }

(2)_.chunk(array, size)

将数组拆分成多个size长度的区块,并将这些区块组成一个新数组。如果array无法被分割成全部等长的区块,那么最后剩余的元素将组成一个区块。

参数:array:需要分割的数组      size:每个数组区块的长度

返回值:返回一个包含拆分区块的新数组

示例

_.chunk([1,2,3,4,5,6,7,8,9], 2);
// => [[1,2], [3,4],[5,6],[7,8],[9]]
 
_.chunk([1,2,3,4,5,6,7,8,9], 3);
// => [[1,2,3], [4,5,6],[7,8,9]]

 (3)_.compact(array)

 创建一个新数组,包含原数组中所有的非假值元素。false, null, 0, "", undefined, 和 NaN 都是被认为是“假值”。

参数:待处理的数组                            返回值:返回一个不含非假值的新数组

示例 

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

(4) _.drop(array, [n=1])

创建一个切片数组,去除array前面的n个元素。

参数: array: 待处理的数组。 n: 要去除的元素个数。默认为1

返回值:返回array剩余切片。

示例

_.drop([1, 2, 3]);
// => [2, 3]
_.drop([1, 2, 3], 2);
// => [3] 
_.drop([1, 2, 3], 5);
// => [] 
_.drop([1, 2, 3], 0);
// => [1, 2, 3]

 (5)_.indexOf(array, value, [fromIndex=0])

返回首次 value 在数组array中被找到的索引值, 如果 fromIndex 为负值,将从数组array尾端索引进行匹配。

参数 :array: 需要查找的数组

           value: 需要查找的值。

           fromIndex: 开始查询的位置。

返回值:  返回目标元素在数组中的索引位置, 没有找到为返回-1。

示例

_.indexOf([1, 2, 1, 2], 2);
// => 1
 
// Search from the `fromIndex`.
_.indexOf([1, 2, 1, 2], 2, 2);
// => 3

(6)_.uniq(array)

创建一个去重后的array数组副本。只有第一次出现的元素才会被保留。

参数:array: 要检查的数组     返回值: 返回去重后的新数组。

示例

_.uniq([2, 1, 2]);
// => [2, 1]

Guess you like

Origin blog.csdn.net/qq_50748038/article/details/126469370