String、Math、Array常用方法

161 阅读2分钟

知识回顾与整理,如有疏漏,敬请指摘,共同进步!
详细内容可以去MDN搜索

String

String.prototype.charAt(index):从一个字符串中返回指定的字符。
若没有指定index,则为0 。

String.prototype.charCodeAt(index):返回指定位置的字符的unicode编码。

String.prototype.concat():字符串合并,形成新的字符串然后返回。
可以用于数组中字符串元素的拼接。

"".concat({})    // [object Object]

String.prototype.includes():返回指定字符串是否有在字符串中出现。返回true/false

String.prototype.indexOf(str):返回字符串中,出现指定字符串的位置(索引)。如果没有找到,则返回-1;

String.prototype.match(): 检索返回一个字符串匹配正则表达式的结果。

String.prototype.replace():替换字符串,返回新字符串,不会更改旧的字符串。

String.prototype.slice(beginIndex[, endIndex]):提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。

String.prototype.split():使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。

String.prototype.toString():toString()方法返回指定对象的字符串形式。

String.prototype.trim():删除字符串两端的空白字符。

Math

ceil max min pow round random

ceil:返回大于或等于一个给定数字的最小整数。

floor:返回小于或等于一个给定数字的最大整数。

max min:(数组)最大值最小值。

random(): 返回一个浮点数, 伪随机数在范围从0到小于1,也就是说,从0(包括0)往上,但是不包括1(排除1)

round:四舍五入返回整数。

Math.pow(base, exponent):pow() 函数返回基数(base)的指数(exponent)次幂

Array

push:添加元素到数组的末尾

let newLength = fruits.push('Orange')
// ["Apple", "Banana", "Orange"]

pop:删除数组末尾的元素

let last = fruits.pop() // remove Orange (from the end)
// ["Apple", "Banana"]

shift:删除数组头部元素

let first = fruits.shift() // remove Apple from the front
// ["Banana"]

unshift:添加元素到数组的头部

let newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"]

indexOf:找出某个元素在数组中的索引

fruits.push('Mango')
// ["Strawberry", "Banana", "Mango"]

let pos = fruits.indexOf('Banana')
// 1

splice:通过索引删除某个元素

let removedItem = fruits.splice(pos, 1) // this is how to remove an item

// ["Strawberry", "Mango"]

slice:复制一个数组

let shallowCopy = fruits.slice() // this is how to make a copy
// ["Strawberry", "Mango"]