在 js 中, 对于字符串处理和其他语言不一样 ,它有一部分数组的特点,但是不完全有, 因此要把它通过 split()方法转成字符串数组才能像正常数组那样操作!
->我们以使用字符串的索引访问字符串中的字符。第一个字符的索引是 0,它递增 1。因此,我们可以像这样访问字符串的每个字符,如
let a = 'star';
for(let i = 0 ; i < a.length ; i++){
console.log(a[i]); // s t a r
}
但是不能直接对字符串根据索引赋值操作,如:
let a = 'star';
for(let i = 0 ; i < a.length ; i++){
console.log(a[i]); // s t a r
}
a[0] = 'b';
console.log(a); // star
也不能把其看作正常数组使用 push ,pop 等操作 ,如:
let a = 'star';
for(let i = 0 ; i < a.length ; i++){
console.log(a[i]); // s t a r
}
a[0] = 'b';
console.log(a); // star
a.push('a'); // error : a.push is note a function
因此需要将其转成字符串数组,通过 split() 方法
let a = 'star';
a = a.split('');
for(let i = 0 ; i < a.length ; i++){
console.log(a[i]); // s t a r
}
a[0] = 'b';
console.log(a); // ['b','t','a','r']
a.push('a');
console.log(a); //['b','t','a','r','a']