最近今天在寫一個“刪除字串中重複字串”的函數,代碼如下:
開門見山,重點
string.charAt(index) 代替 string[index]
function removeReapeatStrings1(str) {var str = trim(str);var len = str.length;var once = str;if (len !== 0) {var fromindex = 1;var index = -1;var i = 0;for (index = str.indexOf(str[0], fromindex); (index !== -1) && (2 * index <= len); ) {// check the characters between 1 and indexfor (i = 1; i < index; ++i) {if (str[i] !== str[index + i]) {break;}}// if we found a unique string, stop for exit functionif (i === index) {once = str.slice(0, index);break;}// not found look for a same character as the first character of strfromindex = index + 1;index = str.indexOf(str[0], fromindex);}}return once;}alert(removeReapeatStrings1('北京'));alert(removeReapeatStrings1('北京北京'));alert(removeReapeatStrings1('大興大地大興大地'));
上面代碼在非IE瀏覽器,運行正常,分別alert 北京,北京,大興大地,但在IE下,奇蹟發生了alert 北京, 北京北京, 大興大地大興大地。
왜?どうして?
於是各種調試(我用的是簡單直觀地alert調試法,不要見笑)
最後發現 str[0] 在萬惡的IE下,竟然是undefined!?所學知識在腦中不斷閃現,似乎記起來在《High Performance Javascript》最後幾章有這樣的提示:不要用簡短運算式代替原生函數(如果有相應的)。天哪?果斷所有的string[index],全部用string.charAt(index)代替。
正確相容IE和非IE代碼如下:
function removeReapeatStrings1(str) {var str = trim(str);var len = str.length;var once = str;if (len !== 0) {var fromindex = 1;var index = -1;var i = 0;for (index = str.indexOf(str.charAt(0), fromindex); (index !== -1) && (2 * index <= len); ) {// check the characters between 1 and indexfor (i = 1; i < index; ++i) {if (str.charAt(i) !== str.charAt(index + i)) {break;}}// if we found a unique string, stop for exit functionif (i === index) {once = str.slice(0, index);break;}// not found look for a same character as the first character of strfromindex = index + 1;index = str.indexOf(str.charAt(0), fromindex);}}return once;}
貼一段文字,from http://stackoverflow.com/questions/5943726/string-charatx-or-stringx
There are two ways to access an individual character in a string. The first is the charAt method:
return 'cat'.charAt(1); // returns "a"
The other way is to treat the string as an array, where each index corresponds to an individual character:
return 'cat'[1]; // returns "a"
The second way (treating the string as an array) is not part of ECMAScript 3; it's a JavaScript and ECMAScript 5 feature (and not supported in all browsers).
In both cases, attempting to set an individual character won't work. Trying to set a character through charAt results in an error, while trying to set a character via indexing does not throw an error, but the string itself is unchanged.
So, as you might have figured out by now, charAt() is better from a compatibility perspective.
String.charAt() is the standard and it works in all the browsers. In non-IE browsers you may use bracket notation to access characters but IE doesn't support it. (Not sure whether they have implemented that with the latest versions).
If somebody really wants to use bracket notication. It's wise to convert the string to char array in order to make it compatible with any browser.
面對字串,請謙卑地使用charAt吧。理由
1、正確性
2、相容性
全篇完結。