常用方法1

153 阅读5分钟

一、字符串操作方法

大小写转换:toLowerCase()、toLocaleLowerCase()、toUpperCase()、toLocaleUpperCase()
比较两个字符串:localeCompare()
字符方法:chartAt()与charCodeAt()
转码:fromCharCode()
去空格:trim()
1. 查找
IndexOf、lastIndexOf

搜索给定的子字符串,找到则返回位置,否则返回-1

let strVal = "hello world"
strVal.indexOf("o")        
strVal.lastIndexOf("o")   

strVal.startsWith('world',6)
strVal.endsWith('Hello',5)  
strVal.includes('Hello',6)
ES6新增includes()、startsWith()、endsWith()
includes()   返回布尔值,表示是否找到了参数字符串
startsWith() 返回布尔值,表示参数字符串是否在源字符串的头部
endsWith()   返回布尔值,表示参数字符串是否在源字符串的尾部
2. 操作
截取(substring,slice,substr)

substring,slice,substr,repeat均返回子字符串,不会修改原来的字符串

let strVal = "hello world"
strVal.substring(3,7)      
连接(concat)、重复(repeat)

repeat将原字符串重复n次

let str2 = "world!";
let newstr1 = str1.concat(str2)
let newstr2 = str1.repeat(2)
3. 模式匹配
match \ search \ replace \ split

match()

参数:一个正则表达式或RegExp对象; 返回一个数组

let text = "cat, bat, sat, fat"
let pattern = /.at/
let matches = text.match(pattern)      

search()

参数:一个正则表达式或RegExp对象; 返回字符串中第一个匹配项的索引,如果没有找到,则返回-1

var text = "cat, bat, sat, fat";  
var pos = text.search(/at/); 
alert(pos); 

replace()

参数:一个RegExp对象或者一个字符串或一个函数

利用replace()进行替换的时候,如果传入的是字符串,则只会替换第一个子字符串,

要想替换所有的子字符串,则需要传入一个正则表达式,而且要指定全局(g)标志

var text = 'cat , bat , sat , fat';
var result = text.replace('at','ond');
console.log(result); 
result = text.replace(/at/g,'ond');
console.log(result); 

split()

参数:用于分隔字符串的分隔符,数字(可选,用于指定数组的大小)

返回一个数组

var str4 = '2013-11-29-23-07';
alert( str4.split('-', 3) );            //2013, 11, 29

二、数组方法

一类不会改变原数组的方法(8个):

ES5:slice、join、toLocateString、toStrigin、cancat、indexOf、lastIndexOf、
ES7:includes

下面这类会改变原数组的值的方法:

ES5: pushpopshiftunshiftsplicereversesort、
ES6: copyWithin、fill;
1.查找
IndexOf、lastIndexOf、includes

搜索给定值索引,找到则返回位置,否则返回-1

[3, 2, 3].indexOf(2)  // 1

判定给定值,返回布尔值

[1, 2, 3].includes(3) // true
2.遍历
forEach、map、every、some
forEach -- 遍历循环,和for循环没有太大差别; 这个方法没有返回值
map     -- 对数组中的每个元素进行处理,返回新的数组

every -- 检测数组所有元素是否都符合判断条件,都符合条件,则返回true。
some  -- 数组中的是否有满足判断条件的元素, 有一项符合条件,则返回true。

filter -- 过滤原始数组,返回新数组,如果没有,返回空数组
find   -- 判断数组是否含有某值,一旦查找到,马上跳出循环,返回符合条件的数组元素

findIndex -- 与fine相同,输出符合条件的数组元素序列
let arr = [1,2,3,4,5,6,7,8,9];
let newArr = arr.map(function(item,index){
    return item * 2
})

let newArr = arr.every(function(item,index){
    return item>2 && item<5
})

let filterNewArr = arr.filter(function(item,index){
    return item % 2 === 0
})
reduce、reduceRight

reduce()和reduceRight(),这两个方法都会迭代数组中的所有项,然后生成一个最终返回值

参数( 函数function(prev,cur,index,array){ }, 初始值)

// 所有项相加
var arr = [0,1,2,3,4];
arr.reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;         //20
}, 10);   

keys()&values()&entries() 遍历键名、遍历键值、遍历键名+键值

定义:三个方法都返回一个新的 Array Iterator 对象,对象根据方法不同包含不同的值。

3.截取
slice、splice

slice 浅拷贝数组的元素 (begin, end(不包括)),返回一个新数组

splice(起始位置,要删除的数目,要插入的任意数量的项目), 返回值是删除的元素

let a= ['hello','world'];
let b=a.slice(0,1);     // ['hello']
[1, 2, 3, 4, 5, 6, 7].slice(3, 6)

// 从位置0开始,删除2个元素后插入7,8,9
const arr = [1, 2, 3, 4, 5];
arr.splice(0, 2, 7,8,9);
4.添加、删除、反转
push、pop、shift、unshift
arr.push  从末尾添加元素,返回值为添加完后的数组的长度
arr.pop   从后面删除元素,只能是一个,返回值是删除的元素

arr.shift   从前面删除元素,只能删除一个 返回值是删除的元素
arr.unshift 从前面添加元素, 返回值是添加完后的数组的长度

arr.reverse  反转 将数组中元素的位置颠倒,并返回该数组,该方法会改变原数组
5.排序

arr.sort排序 并返回这个数组

例1: 数组元素为数字的升序、降序:

var array =  [10, 1, 3, 4,20,4,25,8]
 array.sort(function(a,b){
   return a-b
 })

 array.sort(function(a,b){
   return b-a
 })

例2:数组多条件排序(按照id升序,按照age升序)

 var array = [{id:10,age:2},{id:5,age:4},{id:6,age:10},{id:9,age:6},{id:2,age:8},{id:10,age:9}];
 array.sort(function(a,b){
     if(a.id === b.id){
         return b.age - a.age
     }else{
         return a.id - b.id
     }
 })

例3:自定义比较函数

var array = [{name:'Koro1'},{name:'Koro1'},{name:'OB'},{name:'Koro1'},{name:'OB'},{name:'OB'}];
array.sort(function(a,b){
    if(a.name === 'Koro1'){
        return -1
    }else{
      return 1
    }
})
// [{"name":"Koro1"},{"name":"Koro1"},{"name":"Koro1"},{"name":"OB"},{"name":"OB"},{"name":"OB"}] 
6.连接、转换、填充
concat、join、fill

concat() 方法用于合并两个或多个数组,此方法不会更改现有数组,而是返回一个新数组

join() 元素是通过指定的分隔符进行分隔的,返回一个字符串

toString() 数组转字符串 不推荐与join方法相比没有优势,也不能自定义字符串的分隔符,因此不推荐使用

fill() 替换指定索引范围内的数组的值; 如果没有提供范围,该方法将替换所有数组的值

['Brian', 'Matt', 'Kate'].join(', ')
// 参数:(要填充数组的值, 开始位置-可选, 结束位置-可选)

['a', 'b', 'c'].fill(7);                // [7, 7, 7]   
   
['a', 'b', 'c'].fill(7, 1, 2);          // ['a', 7, 'c']

三、object方法

1. Object.assign

常用来合并对象

const obj3 = Object.assign(obj1, obj2)   // 合并
const obj4 = Object.assign({}, obj1)     // 克隆了obj1对象

2. 枚举对象
  • Object.keys: 返回一个数组,是可遍历属性的键名
  • Object.values: 返回一个数组,是可遍历属性的键值
  • Object.entries:返回一个数组,是键值对数组
var obj = { foo: 'bar', baz: 42 }
Object.keys(obj)    // ["foo", "baz"]
Object.values(obj)  // ["bar", 42]
Object.entries(obj) // [ ["foo", "bar"], ["baz", 42] ]
3. hasOwnProperty:

返回一个布尔值,判断是否有指定的键

const obj = { a: 2 }
obj.hasOwnProperty('a') // true