JavaScript常用方法汇总

发表于:2020-10-04
字数统计:7k 字
阅读时长:17 分钟
阅读量:211

Array

去除数组重复元素

const arr = [3,4,4,5,4,6,5,7];
console.log(new Set(arr)); // {3,4,5,6,7}
const a = Array.from(new Set(arr)) // [3, 4, 5, 6, 7]

sort()

对数组元素进行排序(改变原数组)

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.sort()) // [3, 4, 4, 4, 5, 5, 6, 7]

reverse()

反转数组中的元素

const arr = [3,4,4,5,4,6,5,7];
conosle.log(arr.reverse());  // [7, 6, 5, 5, 4, 4, 4, 3]

delete()

删除数组或对象的元素,会形成空位(改变原数组)

//数组
const arr = [3,4,4,5,4,6,5,7];
delete arr[0]
console.log(arr) // [empty, 4, 4, 5, 4, 6, 5, 7]
//对象
const obj = {name: 'jack',age: '24', gender: '男'};
delete obj.gender;
console.log(obj); // {name: "jack", age: "24"}

shift()

删除数组第一个元素,并返回第一个元素的值(改变原数组)

let arr = [3,4,4,5,4,6,5,7];
let a = arr.shift() // 3
console.log(arr) // [4, 4, 5, 4, 6, 5, 7]

unshift()

想数组起始处添加一个或多个元素,并返回新的长度(改变原数组)

let arr = [3,4,4,5,4,6,5,7];
let a = arr.unshift(8); // 添加一个元素
arr.unshift(1,2);  // 添加多个元素
console.log(a)  // 9(返回数组的新长度)
console.log(arr)  // [1, 2, 8, 3, 4, 4, 5, 4, 6, 5, 7]

push()

在数组末端添加一个或多个元素,并返回添加元素后的数组长度(改变原数组)

let arr = [3,4,4,5,4,6,5,7];
let a = arr.push(1,2)
console.log(a) // 10 返回数组的新长度
console.log(arr) // [3, 4, 4, 5, 4, 6, 5, 7, 1, 2]

valueOf()

返回数组本身

let arr = [3,4,4,5,4,6,5,7];
console.log(arr.valueOf()) // [3, 4, 4, 5, 4, 6, 5, 7]

toString()

把数组转为字符串

let arr = [3,4,4,5,4,6,5,7];
console.log(arr.toString()) // 3,4,4,5,4,6,5,7

concat()

连接两个或多个数组(字符串适用)

// 数组
let a = [1,2]
let b = [3,4]
let c = [5,6]
let d = a.concat(b)
let e = a.concat(b, c)
console.log(d) // [1, 2, 3, 4]
console.log(e) // [1, 2, 3, 4, 5, 6]

// 字符串
let x = 'abc'
let y = 'def'
let z = x.concat(y)
console.log(z) // abcdef

join()

用指定分隔符对数组元素进行分割

let arr = [3,4,4,5,4,6,5,7];
console.log(arr.join('-')) // 3-4-4-5-4-6-5-7
console.log(arr.join(' ')) //  3 4 4 5 4 6 5 7

slice()

从以有的数组中返回选定的元素, 参数1起始下标,参数2结束下标(适用于字符串)

// 数组
let a = arr.slice(0, 4)
console.log(a) // [3, 4, 4, 5]

// 字符串
let x = 'abcdefg'
let y = x.slice(0, 4)
console.log(y) // abcd

splice()

从数组中添加/删除元素,然后返回被删除的元素

参数1 必选,规定删除元素的位置,使用负数可从数组结尾处规定位置

参数2 必选,要删除的元素个数

参数3 可选, 向数组添加新元素

let arr = [3,4,4,5,4,6,5,7];
let a = arr.splice(3, 2, 20, 30 )
console.log(a) // [5, 4]
console.log(arr) //  [3, 4, 4, 20, 30, 6, 5, 7]

map()

遍历数组元素,根据遍历结果返回一个新数组(不改变原始数组)

let arr = [3,4,4,5,4,6,5,7];
// 将数组中的元素*3
let a = arr.map(item => item*3) // [9, 12, 12, 15, 12, 18, 15, 21]

forEach()

跟map方法类似,遍历数组,区别是无返回值。

const arr = [3,4,4,5];
arr.forEach((value,index,arr) => {
  console.log(value) // 3 4 4 5
})

for in()

跟 map 方法类似,遍历对象或者数组。

但值得注意的是 for in 循环返回的值都是数据结构的 键值名 。遍历对象返回的对象的key值,遍历数组返回的数组的下标(key)。

//数组
const arr = [1,3,5];
for(let i in arr) {
  console.log(i) // 0 1 2
  console.log(arr[i]) // 1 3 5
}

// 对象
const obj = {a: 'A', b: 'B', c: 'C' };
for (let key in obj) {
  console.log(key) // a b c
}

filter()

对数组过滤

let arr = [3,4,4,5,4,6,5,7];
let a = arr.filter(item => item > 4)
console.log(arr) // [5, 6, 5, 7]

reduce()

方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

const arr = [3,4,4,5,4,6,5,7];
const total = arr.reduce((pre, cur) => {
  return pre + cur
})
console.log(total) // 38

reduceRight()

与reduce用法一致(例子略过)

indexOf()

回给定元素在数组中的第一次出现的位置,如果没有则返回-1(同样适用于字符串)。

let arr = [3,4,4,5,4,6,5,7];
console.log(arr.indexOf(4)) // 1

lastIndexOf()

返回给定元素在数组中最后一次出现的位置,没有返回-1(同样适用于字符串)。

let arr = [3,4,4,5,4,6,5,7];
console.log(arr.lastIndexOf(4)) // 4

shuffle()

用洗牌算法随机打乱一个集合。

const arr = [1,2,3,4,5,6,7,8,9,10];

const shuffle = ([...arr]) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr;
};
console.log(shuffle(arr)) //  [5, 8, 10, 1, 3, 9, 7, 6, 4, 2]

flat()

接收一个数组,无论这个数组里嵌套了多少个数组,最后都会把其变成一个一维数组(扁平化)。

const arr = [[1,2,3],[4,5,[6,7]]];
const a = arr.flat(3);
console.log(a); // [1, 2, 3, 4, 5, 6, 7]

isArray()

用来判断是不是数据是不是一个数组,返回值为true或false。

const arr = [3,4,4,5,4,6,5,7];
console.log(Array.isArray(arr)) // true

copyWithin()

从数组的指定位置拷贝元素到数组的另一个指定位置中。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.copyWithin(4,2)) // [3, 4, 4, 5, 4, 5, 4, 6]

find()

获取数组中大于 3 的第一个元素

const arr = [3,4,4,5,4,6,5,7];
const a = arr.find(item => item > 3);
console.log(a); // 4

String

charAt()

返回指定位置的字符

const str = 'hello world';
console.log(str.charAt(7))  // o

chaCodeAt()

用于返回指定位置的字符的Unicode编码

const str = 'hello world';
console.log(str.charCodeAt(7))  // 111

match()

用于在字符串内检索指定的值或找到一个或多个正则表达式的匹配

// 使用正则匹配字符串
const strs = '1.hello world, 2.are you ok?';
console.log(strs.match(/\d+/g)) // ["1", "2"]

replace()

替换匹配的字符串,可使用正则表达式。

const str = 'hello world world';
console.log(str.replace('world', 'friend'))  // hello friend world 
console.log(str.replace(/world/g, 'friend'))  // hello friend friend

splice()

将字符串分割成数组

const str = 'hello world';
console.log(str.split('')) // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
console.log(str.split('', 5)) //  ["h", "e", "l", "l", "o"]

toLocaleLowerCase() & toLowerCase()

将字符串转换成小写。

const str = 'hello world';
console.log(str.toLocaleLowerCase())  // hello world
console.log(str.toLowerCase())  //  hello world

toLocaleUpperCase() & toUpperCase()

将字符串转换成大写。

const str = 'hello world';
console.log(str.toLocaleUpperCase())  // HELLO HELLO WORLD
console.log(str.toUpperCase())  // HELLO HELLO WORLD

substr()

用于从起始索引号提取字符串中指定数目的字符。

const str = 'hello world';
console.log(str.substr(2))  // llo world
console.log(str.substr(2, 7))  // llo wor

substring()

用于提取字符串中两个指定索引号之间的字符。(与 slice() 和 substr() 方法不同的是, substring() 不接受负的参数。)

const str = 'hello world';
console.log(str.substring(2))   // llo world
console.log(str.substring(2, 7))  //  llo w

trim()

去除字符串两端的空格

const str = ' hello world ';
console.log(str.trim())   // hello world

Date对象的用法

首先需要定义一个变量:

const date = new Date();

接下来就可以直接使用常见的Date对象方法。

  • Date(): 返回当日的日期和时间;
  • getDate(): 从Date对象返回一个月中的某一天(1~31)console.log(date.getDate());
  • getDay():从Date对象返回一周中的某一天(0~6);
  • getMonth(): 从Date对象返回月份(0~11);
  • getFullYear(): 从Date对象以四位数字返回年份;
  • getYear():可以使用getFullYear()代替;
  • getHours(): 返回Date()对象的小时(0~23);
  • getMinutes(): 返回Date()对象的分钟(0~59);
  • getSeconds(): 返回Date()对象的分钟(0~59);
  • getMillseconds(): 返回Date()对象的毫秒(0~999);
  • getTime(): 返回1970年1月1日至今的时间;
  • getTimezoneOffset(): 返回本地时间与格林威治标准时间(GMT)的分钟差;
  • getUTCDate(): 根据世界时从Date对象返回月中的一天(1~31);
  • getUTCDay(): 根据世界时从Date对象返回周中的一天(1~6);
  • getUTCMonth(): 根据世界时从Date对象返回月份(0~11);
  • getUTCFullYear(): 根据世界时从Date对象返回四位数的年份;
  • getUTCHours(): 根据世界时从Date对象返回对象的小时(0~23);
  • getUTCMinutes(): 根据世界时从Date对象返回对象的分钟(0~59);
  • getUTCSeconds(): 根据世界时从Date对象返回对象的秒钟(0~59);
  • getUTCMillseconds(): 根据世界时从Date对象返回对象的毫秒(0~999);
  • parse(): 返回1970年1月1日午夜到指定日期(字符串)的毫秒数;
  • setDate(): 设置Date对象中月的某一天(1~31);
  • setMonth(): 设置Date对象中月份(0~11);
  • setFullYear(): 设置Date对象中的年份(四位数字);

Math.xx开头的方法

  • Math.ceil(): 对数进行上舍入(天花板函数) 大于等于 x,并且与它最接近的整数。
  • Math.floor(): 对数进行下舍入(地板函数)。
  • Math.max(x,y):返回x,y中的最大值。
  • Math.min(x,y):返回x,y中的最小值。
  • Math.pow(x,y): 返回x的y次方。
  • Math.random() : 返回0-1之间的随机数。
  • Math.round(x): 四舍五入。
  • Math.abs(x):返回数的绝对值。
  • Math.acos(x):返回数的反余弦值。
  • Math.asin(x): 返回数的反正弦值。
  • Math.atan(x):返回数的反正切值。
  • Math.atan2(y,x):返回由x轴到点(x,y)的角度(以弧度为单位)。
  • Math.cos(x): 返回数的余弦值。
  • Math.exp(e): 返回e的指数。
  • Math.log(x):返回数的自然对数(以e为底数)。
  • Math.sin(x):返回数的正弦值。
  • Math.sqrt(x):返回数的平方根。
  • Math.tan(x): 返回角的正切值。
  • Math.toSource():返回该对象的源代码。
  • Math.valueOf(): 返回Math对象的原始值。
1/0