2019-04-21 11:50:48 +08:00

255 lines
12 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<article id="wikiArticle">
<p></p><p></p>
<h2 id="Summary" name="Summary">概述</h2>
<p><strong>charAt()</strong> 方法从一个字符串中返回指定的字符。</p>
<h2 id="Syntax" name="Syntax">语法</h2>
<pre><code class="language-javascript"><em>str</em>.charAt(<em>index</em>)</code></pre>
<h3 id="Parameters" name="Parameters">参数</h3>
<dl>
<dt><code>index</code></dt>
<dd>一个介于0 和字符串长度减1之间的整数。 (0~length-1)</dd>
<dd>如果没有提供索引charAt() 将使用0。</dd>
<dt> </dt>
</dl>
<h2 id="Description" name="Description">描述</h2>
<p>字符串中的字符从左向右索引,第一个字符的索引值为 0最后一个字符假设该字符位于字符串 stringName 中)的索引值为 <code>stringName.length - 1</code>。 如果指定的 index 值超出了该范围,则返回一个空字符串。</p>
<h2 id="Examples" name="Examples">示例</h2>
<h3 id="Example:_Displaying_characters_at_different_locations_in_a_string" name="Example:_Displaying_characters_at_different_locations_in_a_string">例子:输出字符串中不同位置的字符</h3>
<p>下例输出字符串 "<code>Brave new world</code>" 不同位置处的字符:</p>
<pre><code class="language-js">var anyString = "Brave new world";
console.log("The character at index 0 is '" + anyString.charAt(0) + "'");
console.log("The character at index 1 is '" + anyString.charAt(1) + "'");
console.log("The character at index 2 is '" + anyString.charAt(2) + "'");
console.log("The character at index 3 is '" + anyString.charAt(3) + "'");
console.log("The character at index 4 is '" + anyString.charAt(4) + "'");
console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
</code></pre>
<p>上面代码的输出为:</p>
<pre>The character at index 0 is 'B'
The character at index 1 is 'r'
The character at index 2 is 'a'
The character at index 3 is 'v'
The character at index 4 is 'e'
The character at index 999 is ''
</code></pre>
<h3 id="例子:获取所有字符">例子:获取所有字符</h3>
<p>以下提供了一种确保通过字符串循环总是提供整个字符的方法,即使该字符串包含不在<a class="external" href="https://zh.wikipedia.org/wiki/Unicode%E5%AD%97%E7%AC%A6%E5%B9%B3%E9%9D%A2%E6%98%A0%E5%B0%84#.E5.9F.BA.E6.9C.AC.E5.A4.9A.E6.96.87.E7.A7.8D.E5.B9.B3.E9.9D.A2" rel="noopener">基本多文种平面</a>BMP中的字符。</p>
<pre><code class="language-js">var str = 'A \uD87E\uDC04 Z'; // We could also use a non-BMP character directly
for (var i=0, chr; i &lt; str.length; i++) {
if ((chr = getWholeChar(str, i)) === false) {
continue;
} // Adapt this line at the top of each loop, passing in the whole string and
// the current iteration and returning a variable to represent the
// individual character
alert(chr);
}
function getWholeChar (str, i) {
var code = str.charCodeAt(i);
if (isNaN(code)) {
return ''; // Position not found
}
if (code &lt; 0xD800 || code &gt; 0xDFFF) {
return str.charAt(i);
}
// High surrogate (could change last hex to 0xDB7F to treat high private
// surrogates as single characters)
if (0xD800 &lt;= code &amp;&amp; code &lt;= 0xDBFF) {
if (str.length &lt;= (i+1)) {
throw 'High surrogate without following low surrogate';
}
var next = str.charCodeAt(i+1);
if (0xDC00 &gt; next || next &gt; 0xDFFF) {
throw 'High surrogate without following low surrogate';
}
return str.charAt(i)+str.charAt(i+1);
}
// Low surrogate (0xDC00 &lt;= code &amp;&amp; code &lt;= 0xDFFF)
if (i === 0) {
throw 'Low surrogate without preceding high surrogate';
}
var prev = str.charCodeAt(i-1);
// (could change last hex to 0xDB7F to treat high private
// surrogates as single characters)
if (0xD800 &gt; prev || prev &gt; 0xDBFF) {
throw 'Low surrogate without preceding high surrogate';
}
// We can pass over low surrogates now as the second component
// in a pair which we have already processed
return false;
}
</code></pre>
<p>在允许解构分配的独占JavaScript 1.7+环境如Firefox以下是一个更简洁和更灵活的替代方法它会自动递增一个递增变量如果字符保证它是一个替代对</p>
<pre><code class="language-javascript">var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly
for (var i=0, chr; i &lt; str.length; i++) {
[chr, i] = getWholeCharAndI(str, i);
// Adapt this line at the top of each loop, passing in the whole string and
// the current iteration and returning an array with the individual character
// and 'i' value (only changed if a surrogate pair)
alert(chr);
}
function getWholeCharAndI (str, i) {
var code = str.charCodeAt(i);
if (isNaN(code)) {
return ''; // Position not found
}
if (code &lt; 0xD800 || code &gt; 0xDFFF) {
return [str.charAt(i), i]; // Normal character, keeping 'i' the same
}
// High surrogate (could change last hex to 0xDB7F to treat high private
// surrogates as single characters)
if (0xD800 &lt;= code &amp;&amp; code &lt;= 0xDBFF) {
if (str.length &lt;= (i+1)) {
throw 'High surrogate without following low surrogate';
}
var next = str.charCodeAt(i+1);
if (0xDC00 &gt; next || next &gt; 0xDFFF) {
throw 'High surrogate without following low surrogate';
}
return [str.charAt(i)+str.charAt(i+1), i+1];
}
// Low surrogate (0xDC00 &lt;= code &amp;&amp; code &lt;= 0xDFFF)
if (i === 0) {
throw 'Low surrogate without preceding high surrogate';
}
var prev = str.charCodeAt(i-1);
// (could change last hex to 0xDB7F to treat high private surrogates
// as single characters)
if (0xD800 &gt; prev || prev &gt; 0xDBFF) {
throw 'Low surrogate without preceding high surrogate';
}
// Return the next character instead (and increment)
return [str.charAt(i+1), i+1];
}</code></pre>
<h3 id="示例修复charAt以支持非基本多文种平面BMP字符">示例修复charAt以支持非基本多文种平面BMP字符</h3>
<p>虽然上面的例子对于那些希望支持非BMP字符的用户可能更有用因为它不要求调用者知道任何非BMP字符可能出现在哪里在人们希望的情况下在选择字符 通过索引,将字符串中的替代对作为它们表示的单个字符,可以使用以下:</p>
<pre><code class="language-javascript">function fixedCharAt (str, idx) {
var ret = '';
str += '';
var end = str.length;
var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
while ((surrogatePairs.exec(str)) != null) {
var li = surrogatePairs.lastIndex;
if (li - 2 &lt; idx) {
idx++;
} else {
break;
}
}
if (idx &gt;= end || idx &lt; 0) {
return '';
}
ret += str.charAt(idx);
if (/[\uD800-\uDBFF]/.test(ret) &amp;&amp; /[\uDC00-\uDFFF]/.test(str.charAt(idx+1))) {
// Go one further, since one of the "characters" is part of a surrogate pair
ret += str.charAt(idx+1);
}
return ret;
}</code></pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>ECMAScript 1st Edition.</td>
<td>Standard</td>
<td>Initial definition.</td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.4" hreflang="en" lang="en" rel="noopener">ECMAScript 5.1 (ECMA-262)<br/><small lang="zh-CN">String.prototype.charAt</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td> </td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.charat" hreflang="en" lang="en" rel="noopener">ECMAScript 2015 (6th Edition, ECMA-262)<br/><small lang="zh-CN">String.prototype.charAt</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p></p><div class="blockIndicator warning"><strong><a class="external" href="https://github.com/mdn/browser-compat-data" rel="noopener">We're converting our compatibility data into a machine-readable JSON format</a></strong>.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
<strong><a class="new" href="/zh-CN/docs/MDN/Contribute/Structures/Compatibility_tables" rel="nofollow">Find out how you can help!</a></strong></div>
<div class="htab">
<a id="AutoCompatibilityTable" name="AutoCompatibilityTable"></a>
<ul>
<li class="selected"><a>Desktop</a></li>
<li><a>Mobile</a></li>
</ul>
</div><p></p>
<div id="compat-desktop">
<table class="compat-table">
<tbody>
<tr>
<th>Feature</th>
<th>Chrome</th>
<th>Firefox (Gecko)</th>
<th>Internet Explorer</th>
<th>Opera</th>
<th>Safari</th>
</tr>
<tr>
<td>Basic support</td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
</tr>
</tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
<tbody>
<tr>
<th>Feature</th>
<th>Android</th>
<th>Chrome for Android</th>
<th>Firefox Mobile (Gecko)</th>
<th>IE Mobile</th>
<th>Opera Mobile</th>
<th>Safari Mobile</th>
</tr>
<tr>
<td>Basic support</td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
</tr>
</tbody>
</table>
</div>
<h2 id="See_also" name="See_also">相关链接</h2>
<ul>
<li><a href="Reference/Global_Objects/String/indexOf" title="indexOf() 方法返回调用  String 对象中第一次出现的指定值的索引开始在 fromIndex进行搜索。"><code>String.prototype.indexOf()</code></a>, <a href="Reference/Global_Objects/String/lastIndexOf" title="lastIndexOf() 方法返回指定值在调用该方法的字符串中最后出现的位置,如果没找到则返回 -1。从该字符串的后面向前查找从 fromIndex 处开始。"><code>String.prototype.lastIndexOf()</code></a></li>
<li><a href="Reference/Global_Objects/String/split" title="split() 方法使用指定的分隔符字符串将一个String对象分割成字符串数组以将字符串分隔为子字符串以确定每个拆分的位置。"><code>String.prototype.split()</code></a></li>
<li><a href="Reference/Global_Objects/String/charCodeAt" title="charCodeAt() 方法返回0到65535之间的整数表示给定索引处的UTF-16代码单元 (在 Unicode 编码单元表示一个单一的 UTF-16 编码单元的情况下UTF-16 编码单元匹配 Unicode 编码单元。但在——例如 Unicode 编码单元 &gt; 0x10000 的这种——不能被一个 UTF-16 编码单元单独表示的情况下只能匹配 Unicode 代理对的第一个编码单元) 。如果你想要整个代码点的值,使用 codePointAt()。"><code>String.prototype.charCodeAt()</code></a></li>
<li><a href="Reference/Global_Objects/String/fromCodePoint" title="String.fromCodePoint() 静态方法返回使用指定的代码点序列创建的字符串。"><code>String.fromCodePoint()</code></a></li>
<li><a href="Reference/Global_Objects/String/codePointAt" title="codePointAt() 方法返回 一个 Unicode 编码点值的非负整数。"><code>String.prototype.codePointAt()</code></a></li>
</ul>
</article>