// 遍历字符串的几种方法
// 方法一:使用 for 循环
let str = "Hello, world!";
let result = [];
for (let i = 0; i < str.length; i++) {
result.push(str[i]);
}
console.log(result); // ["H", "e", "l", "l", "o", ",", " ", "w", "o", "r", "l", "d", "!"]
// 方法二:使用 for...of 循环 (ES6+)
str = "JavaScript";
result = [];
for (let char of str) {
result.push(char);
}
console.log(result); // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]
// 方法三:使用 Array.from() 方法 (ES6+)
str = "遍历字符串";
result = Array.from(str);
console.log(result); // ["遍", "历", "字", "符", "串"]
// 方法四:使用 split() 方法
str = "split method";
result = str.split('');
console.log(result); // ["s", "p", "l", "i", "t", " ", "m", "e", "t", "h", "o", "d"]
以上代码展示了四种不同的遍历字符串的方法,每种方法都有其适用场景。你可以根据具体需求选择合适的方法。
上一篇:js 遍历数组对象
下一篇:js 对象数组遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站