1. 定义
单引号字符串的内部,可以使用双引号。双引号字符串的内部,可以使用单引号。如果要在单引号字符串的内部,使用单引号(或者在双引号字符串的内部,使用双引号),就必须在内部的单引号(或者双引号)前面加上反斜杠,用来转义。
'Did she say \'Hello\'?'
// "Did she say 'Hello'?"
"Did she say \"Hello\"?"
// "Did she say "Hello"?"
var longString = 'Long '
+ 'long '
+ 'long '
+ 'string';
2. 字符串与数组
字符串可以被视为字符数组,因此可以使用数组的方括号运算符,用来返回某个位置的字符(位置编号从0开始)。但是,字符串与数组的相似性仅此而已。实际上,无法改变字符串之中的单个字符。字符串也无法直接使用数组的方法,必须通过call方法间接使用。
var s = 'hello';
s[0] // "h"
s[1] // "e"
s[4] // "o"
// 直接对字符串使用方括号运算符
'hello'[1] // "e"
var s = 'hello';
delete s[0];
s // "hello"
s[1] = 'a';
s // "hello"
s[5] = '!';
s // "hello"
var s = 'hello';
s.join(' ') // TypeError: s.join is not a function
Array.prototype.join.call(s, ' ') // "h e l l o"
3. length属性
length属性返回字符串的长度,该属性也是无法改变的。
var s = 'hello';
s.length // 5
s.length = 3;
s.length // 5
