在js中数组与字符串常用的几种方法(包含es6新语法)

本文详细介绍了JavaScript中数组和字符串的常用方法,包括ES6的新特性。数组部分涵盖了join/split、reverse、sort、pop/shift、push/unshift、splice/slice等,以及ES6的Array.from、Array.of、fill等。字符串部分涉及charAt、indexOf/lastIndexOf、replace、substr/substring等,以及ES6的includes、startsWith/endsWith、padStart/padEnd和repeat方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.数组常用的方法

join()&split()

解释:将一个数组转换为字符串

​ 将一个字符串分割成数组

let arr1=["a","b","c"]
console.log(arr1.join())//a,b,c
console.log(arr1.join(""))//abc
console.log(arr1.join(:))// a:b:c
-------------------------------------
let str='asdfghj'
console.log(str.split(''))//  ["a", "s", "d", "f", "g", "h", "j"]
console.log(str.split(","))// ["asdfghj"]

reverse()

解释:将数组中元素的顺序颠倒

let arr1=["a","b","c"]
console.log(arr1.reverse()) //["c","b","a"]

案例:将一字符串进行倒序输出

let str="asdfgh";
console.log(str.split("").reverse().join(""))//hgfdsa

sort()

解释:对数组中的元素进行排序(默认排序顺序是根据字符串UniCode码升序排列)

//数组的升序/降序排序
//升序:
let arr=[1,5,6,11,9,4,23]
arr.sort(function(a,b){
    return a-b
})
console.log(arr) //  [1, 4, 5, 6, 9, 11, 23]
//降序:
let arr=[1,5,6,11,9,4,23]
arr.sort(function(a,b){
    return b-a
})
console.log(arr) //  [23, 11, 9, 6, 5, 4, 1]

//对象中对于某个属性的升/降排序
let obj=[{
    name:'zs',
    age:18
},{
    name:'ls',
    age:30
},{
    name:'wv',
    age:20
}]
obj.sort(function(a,b){
    return a.age-b.age
})
console.log(obj)
					/*
					(3) [{…}, {…}, {…}]
					0: {name: "zs", age: 18}
					1: {name: "wv", age: 20}
					2: {name: "ls", age: 30}
					length: 3
					__proto__: Array(0)
					*/

// 降序同理

pop()&shift()

解释:从尾部删除一个元素;并返回删除的最后一个元素

​ 从头部删除一个元素;并返回被删除的第一个元素

let arr=['zhangsan','lisi','wangwu']
    console.log(arr.pop()) //wangwu
    console.log(arr)  //["zhangsan", "lisi"]
--------------------------------------------------
let arr=['zhangsan','lisi','wangwu']
    console.log(arr.shift()) //zhangsan
     console.log(arr)  // ["lisi", "wangwu"]

push()&unshift()

解释:从尾部添加一个或多个元素,并返回新数组的长度

​ 从头部添加一个或多个元素,并返回新数组的长度

let arr=['zhangsan','lisi','wangwu']
    console.log(arr.push("zhaoliu")) // 4
    console.log(arr) // ["zhangsan", "lisi", "wangwu", "zhaoliu"]
------------------------------------------------------
let arr=['zhangsan','lisi','wangwu']
    console.log(arr.unshift("zhaoliu","guanyu")) // 5
    console.log(arr) //["zhaoliu", "guanyu", "zhangsan", "lisi", "wangwu"]

splice()&slice()

解释:

splice(index,number,item1,item2…):可以用于给数组添加、删除(删除元素时,返回的是删除元素的数组)、替换元素,原数组会发生改变

slice [start,end) 返回指定范围的数组元素,返回的是一个子数组,原数组不会发生改变(end为可选参数)

let arr=["zhaoliu", "guanyu", "zhangsan", "lisi", "wangwu"]
//删除第二个索引位置的元素
console.log(arr.splice(2,1))  //["zhangsan"]
//添加第二个位置的元素为“huangzhong”
arr.splice(2,0,'huangzhong')
console.log(arr) ["zhaoliu", "guanyu", "huangzhong", "zhangsan", "lisi", "wangwu"]
//替换第二个位置的元素为“diaochan”
arr.splice(2,1,"diaochan")
console.log(arr)//["zhaoliu", "guanyu", "diaochan", "lisi", "wangwu"]

--------------------------------------------------

let arr=["zhaoliu", "guanyu", "zhangsan", "lisi", "wangwu"]
console.log(arr.slice(2))  //["zhangsan", "lisi", "wangwu"]
console.log(arr.slice(2,4)) //  ["zhangsan", "lisi"]
console.log(arr)//["zhaoliu", "guanyu", "zhangsan", "lisi", "wangwu"]

ES6中新增的一些数组方法

Array.from()

解释: 将得到的结果转换为一个类数组

<ul>
  	 <li></li>
     <li></li>
     <li></li>
     <li></li>
</ul>
let allList=document.querySelectorAll(ul li)
console.log(allList) //是一个列表,无法利用数组的push 方法追加元素
let arr=Array.from(allList)
console.log(arr) //是一个数组,可以利用数组的push 方法追加元素

Array.of()

解释:将不同类型的参数值,放在同一个数组中形成一个新数组

let arr=Array.of(1,true,[1,2,3],{name:'zhangsan'})
console.log(arr) //(4) [1, true, Array(3), {…}]
                /*	0: 1
                    1: true
                    2: (3) [1, 2, 3]
                    3: {name: "zhangsan"}
                    length: 4
                    __proto__: Array(0)*/

array.fill()

解释:用一个固定值替换数组的元素,会修改原数组

array.fill(填充值, 开始填充的位置, 结束填充的位置(不包含))

let arr=[1,2,3,4,5,6,7,8]
arr.fill(0,3,5) //用0填充索引为3,4的位置
console.log(arr) // [1, 2, 3, 0, 0, 6, 7, 8]

indexOf()

解释:查看数组中是否有满足条件的值,有就返回其索引,没有返回-1;

存在一个bug,如果数组中有一个值为NaN,indexOf(NaN)会返回-1;因为NAN!=NAN 所以回返回一个-1;

let arr=['a','b','add','cdd'];
console.log(arr.indexOf('add')) //2

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

array.includes()

解释:判断一个数组是否包含一个指定的值,如果是返回 true,否则false

let arr=[7,5,6,1,NaN];
console.log(arr.inclludes(NaN)) //true

array.entries()

解释:返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)

array.keys()

解释:用于从数组创建一个包含数组键的可迭代对象,返回下标

数组遍历的几种方式

for…(of)

let arr=['a','b','c','d','e']
//遍历得到数组中的值
for(let item of arr){
    console.log(item)// a b c d e
}
//遍历得到数组中的下标
for(let item of arr.keys())
    console.log(item) // 0 1 2 3 4
//利用解构遍历得到数组中的下标与对应的值
for(let [index,item] of arr.entries()){//entrits是数组中的实例
     console.log(index,item)/*
                                 0 "a"
                                 1 "b"
                                 2 "c"
                                 3 "d"
                                 4 "e"
                                 */
    
}

forEach()

解释:没有返回值,不会改变元素,不会返回新数组,只是针对每个元素调用function, function中有三个参数(item,index,self)

let arr=['a','b','c','d','e']
let res = arr.forEach(function(item,index,self){
    console.log(item,index,self)
 /*输出结果:   a 0 (5) ["a", "b", "c", "d", "e"]
              b 1 (5) ["a", "b", "c", "d", "e"]
              c 2 (5) ["a", "b", "c", "d", "e"]
              d 3 (5) ["a", "b", "c", "d", "e"]
              e 4 (5) ["a", "b", "c", "d", "e"]
    */  
})
console.log(res) //undefined

map()

解释:返回一个新数组,函数返回的结果都作为数组中的每一个元素

let arr=[3,4,6,68,9,45]
let arr2=arr.map(function(item,index){
    if(item>10){
        return item
    }
})
console.log(arr2) //[undefined, undefined, undefined, 68, undefined, 45]

filter()

解释:遍历数组,将符合条件的元素组成一个新数组返回

let arr=[3,4,6,68,9,45]
let arr2=arr.filter(function(item,index){
    if(item>10){
        return item
    }
})
console.log(arr2) // [68, 45]

some()

解释:返回一个布尔值,当有一个元素满足条件时就停止遍历并返回true;当全部的元素都不满足要求时,返回false,用于判断数组中是否有元素符合条件

let arr=[3,4,6,68,9,45]
let arr2=arr.some(function(item,index){
    if(item>10){
        return item
    }
})
console.log(arr2) //true

every()

解释:返回一个布尔值,当全部元素满足条件时就停止遍历并返回true;当有一个元素都不满足要求时,返回false,用于判断数组每个元素是否符合条件

let arr=[3,4,6,68,9,45]
let arr2=arr.every(function(item,index){
    if(item>10){
        return item
    }
})
console.log(arr2) //false

2.字符串中常用的方法

charAt()

解释:请左往右检索字符串,从字符串中取得具体的字符

let str='asdfgh'
console.log(str.charAt(2))// d

indexOf()&lastIndexOf()

解释:请左往右检索字符串,返回某个指定的字符串值在字符串中第一次出现的位置,如果要检索的字符串值没有出现,则该方法返回 -1

​ 从右往左检索字符串,返回某个指定的字符串值在字符串中最后一次出现的位置,如果要检索的字符串值没有出现,则该方法返回 -1

let str='swswadfagh'
console.log(str.lastIndexOf('s'))//2

replace()

解释:在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串,返回一个新的字符串 。只能替换一次,如果想实现多次替换,就要多次使用该方法。

let str='hello,world,world'
console.log(str.replace('world','tomorrow'))// hello,tomorrow,world
------------------------------------------------------------------
let str='hello,world,world'
console.log(str.replace(/world/,'tomorrow'))// hello,tomorrow,world

substr()&substring()

解释:在字符串中抽取从 start 下标开始的指定数目的字符,包含两个参数substr(start,length)

​ 提取字符串中介于两个指定下标之间的字符substring [start,end)

let str='hello,javascript'
console.log(str.substr(2,4))// 取出字符串从第二个位置开始长度为4的字符串     llo,
-------------------------------------------------------
let str='hello,javascript'
console.log(str.substring(2,4)) //取出字符串从第二个位置开始,到为第四个位置结束,也就是第2,3个位置的值     ll

includes()

解释:判断字符串中是否含有满足条件的字符串,返回值是一个布尔类型的值,有就返回true,没有就返回false

let str='asdfghhj'
console.log(str.includes('h'))// true

startsWith()&endsWith()

解释:用于判断是字符串以某个或某几个字符开始,返回值是一个布尔值

​ 用于与判断字符串以某个或某几个字符结束,返回值是一个布尔值

let str='hello,world,hello,tomorrow'
console.log(str.startsWith('hello'))  //ture
console.log(str.endsWith('rrow'))  //true

padStart()&padEnd()

解释:在字符串头部填充一些指定的字符或 字符串 ,包含两个参数(length,‘填充的字符’),如果本身长度大于等于length,则不会进行填充,这里的length是填充之后的总长度,长度不够则会一直用填充的字符串进行填充

​ 在字符串尾部填充一些指定的字符或字符串,包含两个参数(length,‘填充的字符’)

let str='he'
console.log(str.padStart(8,'abc'))  //abcabche 
---------------------------------------------
let str='he'
console.log(str.padEnd(8,'abc')) // heabcabc

repeat()

解释:将字符串进行复制, 参数是想要复制的次数

let str='hello'
console.log(str.repeat(2)) //hellohello
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值