JavaScript 字符串遍历
1. 使用for循环
let str = "这是一个比较长的字符串"
for(let i = 0;i<str.length;i++){
console.log(str[i]);
}
2. 使用foreach方法
let str = "这是一个比较长的字符串"
Array.from(str).forEach(element =>{
console.log(element);
})
该方法是先将字符串转换成数组,然后调用数组的forEach
2.1 将字符串转换成数组
let str = "这是一个比较长的字符串"
let arr = Array.from(str)
console.log(arr);
2.2 数组的forEach方法
是一个用来遍历的方法,它可以返回三个参数
let str = "这是一个比较长的字符串"
let arr = Array.from(str)
arr.forEach((element,index,array)=>{
console.log(element,index,array);
}) // 箭头函数写法
arr.forEach(function (element,index,Array) {
console.log(element,index,Array);
}) // 普通函数写法
除非抛出异常,否则没有办法停止或中断
forEach()
循环。如果有这样的需求,则不应该使用forEach()
方法。
3 使用for…of循环
let str = "这是一个比较长的字符串"
for(let s of str){
console.log(s);
}