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"

Array.prototype.join.call(s, " ") // => "J a v a S c r i p t"

Array.prototype.filter.call(s, // 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

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/27661.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1