JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

7.12 Strings As Arrays


7.12 Strings As Arrays

In ECMAScript 5 (and in many recent browser implementations—including IE8— prior to ECMAScript 5), strings behave like read-only arrays. Instead of accessing individual characters with the charAt() method, you can use square brackets:

var s = test; s.charAt(0) // => "t" s[1] // => "e"

The typeof operator still returns “string” for strings, of course, and the Array.isArray() method returns false if you pass it a string.

The primary benefit of indexable strings is simply that we can replace calls to charAt() with square brackets, which are more concise and readable, and potentially more efficient. The fact that strings behave like arrays also means, however, that we can apply generic array methods to them. For example:

s = "JavaScript", " ") // => "J a v a S c r i p t", // Filter the characters of the string

function(x) {

return x.match(/[^aeiou]/); // Only match nonvowels

}).join("") // => "JvScrpt"

Keep in mind that strings are immutable values, so when they are treated as arrays, they are read-only arrays. Array methods like push(), sort(), reverse(), and splice() modify an array in place and do not work on strings. Attempting to modify a string using an array method does not, however, cause an error: it simply fails silently.

7.12 Strings As Arrays | 161

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1