<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ 数组 - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ freeCodeCamp 是一个免费学习编程的开发者社区，涵盖 Python、HTML、CSS、React、Vue、BootStrap、JSON 教程等，还有活跃的技术论坛和丰富的社区活动，在你学习编程和找工作时为你提供建议和帮助。 ]]>
        </description>
        <link>https://www.freecodecamp.org/chinese/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ 数组 - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/chinese/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 23 May 2026 08:28:45 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/chinese/news/tag/arrays/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ 如何在 JavaScript 数组中插入元素 ]]>
                </title>
                <description>
                    <![CDATA[ 数组数据类型是处理有序值列表时最常用的数据类型之一。 每个值都被称为具有唯一 id 的元素。它存储可以通过单个变量访问的各种数据类型的元素。 在实践中，一个数组可以包含一个用户列表，我们可能需要在最后一个元素之后、第一个元素之前或数组中的任何指定点添加一个元素到数组中。 本文将向你展示如何使用 JavaScript 将元素插入到数组中。如果你赶时间，以下是我们将在本文中深入讨论的方法： // 添加到数组的开头 Array.unshift(element); // 添加到数组的末尾 Array.push(element); // 添加到指定位置 Array.splice(start_position, 0, new_element...); // 使用 concat 方法添加而不改变原始数组 let newArray = [].concat(Array, element);  * 当你想在数组末尾添加一个元素时，请使用 push()。  * 如果你需要在数组的开头添加一个元素，请使用 unshift()。  * 如果要将元素添加到数组的特定位置，请使用 splice() ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/how-to-insert-an-element-into-an-array-in-javascript/</link>
                <guid isPermaLink="false">63285db45ef0a407fd630099</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chengjun.L ]]>
                </dc:creator>
                <pubDate>Mon, 10 Jul 2023 04:16:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/09/pawel-czerwinski-dYjFmiQb_aE-unsplash.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p data-test-label="translation-intro">
        <strong>原文：</strong> <a href="https://www.freecodecamp.org/news/how-to-insert-an-element-into-an-array-in-javascript/" target="_blank" rel="noopener noreferrer" data-test-label="original-article-link">Push into an Array in JavaScript – How to Insert an Element into an Array in JS</a>
      </p><p>数组数据类型是处理有序值列表时最常用的数据类型之一。</p><p>每个值都被称为具有唯一 <code>id</code> 的元素。它存储可以通过单个变量访问的各种数据类型的元素。</p><p>在实践中，一个数组可以包含一个用户列表，我们可能需要在最后一个元素之后、第一个元素之前或数组中的任何指定点添加一个元素到数组中。</p><p>本文将向你展示如何使用 JavaScript 将元素插入到数组中。如果你赶时间，以下是我们将在本文中深入讨论的方法：</p><pre><code>// 添加到数组的开头
Array.unshift(element);

// 添加到数组的末尾
Array.push(element);

// 添加到指定位置
Array.splice(start_position, 0, new_element...);

// 使用 concat 方法添加而不改变原始数组
let newArray = [].concat(Array, element);
</code></pre><ul><li>当你想在数组末尾添加一个元素时，请使用 <code>push()</code>。</li><li>如果你需要在数组的开头添加一个元素，请使用 <code>unshift()</code>。</li><li>如果要将元素添加到数组的特定位置，请使用 <code>splice()</code>。</li><li>最后，当你想保持原始数组时，可以使用 <code>concat()</code> 方法。</li></ul><h2 id="-unshift-">如何使用 unshift() 方法添加到数组的开头</h2><p>在 JavaScript 中，你可以使用 <code>unshift()</code> 方法将一个或多个元素添加到数组的开头，并在添加新元素后返回数组的长度。</p><p>如果我们有一个国家数组，并且想在当前第一个索引 <code>0</code> 处的 “Nigeria” 之前添加一个国家，我们可以使用 <code>unshift()</code> 方法来完成，如下所示：</p><pre><code>const countries = ["Nigeria", "Ghana", "Rwanda"];

countries.unshift("Kenya");

console.log(countries); // ["Kenya","Nigeria","Ghana","Rwanda"]
</code></pre><p>我们还可以使用 <code>unshift()</code> 方法添加多个元素：</p><pre><code>const countries = ["Nigeria", "Ghana", "Rwanda"];

countries.unshift("South Africa", "Mali", "Kenya");

console.log(countries); // ["South Africa","Mali","Kenya","Nigeria","Ghana","Rwanda"]
</code></pre><p>在我们对 <code>unshift()</code> 方法的解释中，我们还声明它返回新数组的长度，如下所示：</p><pre><code>const countries = ["Nigeria", "Ghana", "Rwanda"];

let countriesLength = countries.unshift("South Africa", "Mali", "Kenya");

console.log(countriesLength); // 6
</code></pre><h2 id="-push-">如何使用 push() 方法推送到数组的末尾</h2><p><code>push()</code> 方法类似于 <code>unshift()</code> 方法，因为它将元素添加到数组的末尾而不是开头。它返回新数组的长度，并且与 <code>unshift()</code> 方法一样，可用于添加多个元素。</p><p>让我们再次尝试相同的示例，但这次使用 <code>push()</code> 方法将它们添加到数组的末尾：</p><pre><code>const countries = ["Nigeria", "Ghana", "Rwanda"];

countries.push("Kenya");

console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya"]

countries.push("South Africa", "Mali");

console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya","South Africa","Mali"]
</code></pre><p>我们可以用它来获取新数组的长度：</p><pre><code>const countries = ["Nigeria", "Ghana", "Rwanda"];

let countriesLength = countries.push("Kenya");

console.log(countriesLength); // 4
</code></pre><h2 id="-splice-">如何使用 splice() 方法将元素添加到数组中的指定位置</h2><p>到目前为止，我们只看到了如何将元素添加到数组的开头或结尾，但是你可能想知道如何将元素添加到数组中的特定位置。好吧，你可以使用 <code>splice()</code> 方法来做到这一点。</p><p><code>splice()</code> 方法是一种通用方法，用于通过在数组的指定位置删除、替换或添加元素来更改数组的内容。本节将介绍如何使用此方法将元素添加到特定位置。</p><p>例如，考虑以下国家数组，其中包含按字母顺序排列的三个元素（国家）：</p><pre><code>const countries = ["Ghana", "Nigeria", "Rwanda"];
</code></pre><p>假设我们要添加 “Kenya”，按照字母顺序，它应该放在第二个位置，索引 <code>1</code>（在 Ghana 之后和 Nigeria 之前）。在这种情况下，我们将使用 <code>splice()</code> 方法，语法如下：</p><pre><code>Array.splice(start_position, 0, new_element...);
</code></pre><ul><li><code>start_position</code> 指定了我们希望将新元素插入到数组中的位置的索引。如果有多个元素，它指定插入的元素将从哪里开始。</li><li>如果我们想添加元素到数组中，我们将第二个参数设置为零（<code>0</code>），指示 <code>splice()</code> 方法不要删除任何数组元素。</li><li>以下参数或元素可能不止一个，因为这些是我们要在指定位置添加到数组中的元素。</li></ul><p>例如，让我们在国家数组中将 “Kenya” 放在 “Ghana” 之后：</p><pre><code>const countries = ["Ghana", "Nigeria", "Rwanda"];

countries.splice(1, 0, 'Kenya');

console.log(countries); // ["Ghana","Kenya","Nigeria","Rwanda"]
</code></pre><figure class="kg-card kg-image-card"><img src="https://paper-attachments.dropbox.com/s_8F843EE332F48B356BFA84EB69212DF653EB2859C5739E7748DB9362133DCFB7_1658069550677_illustration.jpg" class="kg-image" alt="s_8F843EE332F48B356BFA84EB69212DF653EB2859C5739E7748DB9362133DCFB7_1658069550677_illustration" width="600" height="400" loading="lazy"></figure><p>就像我们对其他方法所做的那样，我们也可以添加多个元素：</p><pre><code>const countries = ["Ghana", "Nigeria", "Rwanda"];

countries.splice(1, 0, 'Kenya', 'Mali');

console.log(countries); // ["Ghana","Kenya","Mali","Nigeria","Rwanda"]
</code></pre><p>请注意，前面的方法返回新数组的长度，但 <code>splice()</code> 方法更改了原始数组。它不会删除任何元素，因此它返回一个空数组。</p><h2 id="-concat-">如何使用 concat() 方法将元素添加到数组</h2><p>我们可以使用 <code>concat()</code> 方法将元素添加到数组中，而无需改变或更改原始数组。如果我们不希望原始数组受到影响，则创建一个新数组是一种更好的方法。</p><p>我们可以使用此方法根据放置元素的位置将元素添加到数组的开头和结尾：</p><pre><code>const countries = ["Ghana", "Nigeria", "Rwanda"];

let newCountries = [].concat("Mali", countries, "Kenya");

console.log(newCountries); // ["Mali","Ghana","Nigeria","Rwanda","Kenya"]
</code></pre><p><code>concat()</code> 方法还允许我们将两个（或更多）数组连接到一个新数组中：</p><pre><code>const africanCountries = ["Ghana", "Nigeria", "Rwanda"];
const europeanCountries = ["Germany", "France", "spain"];

let countries = [].concat(africanCountries, europeanCountries);

console.log(countries); // ["Ghana","Nigeria","Rwanda","Germany","France","spain"]
</code></pre><h2 id="-"><strong>总结</strong></h2><p>在本文中，我们学习了使用 <code>splice()</code> 方法将元素添加到数组的开始、末尾或任何位置的各种方法。</p><p>我们还了解到 <code>concat()</code> 方法允许我们在不改变原始数组的情况下添加元素。</p><p>你可以使用任何你需要的方法。</p><p>祝你编程快乐！</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript 范围——如何在 JS ES6 中用 .from() 创建一个数字数组 ]]>
                </title>
                <description>
                    <![CDATA[ .from() 方法是 JavaScript ES6 中 Array 对象的一个静态方法。它从一个类似数组或可迭代的对象（如 map 和 set ）创建一个新的、浅拷贝的数组实例。 这个方法从任何具有长度属性的对象中返回一个数组。你可以用它来创建一个指定范围内的数字数组。 在这篇文章中，你将了解 .from() 静态方法是什么，它是如何工作的，以及你如何在 JavaScript 中创建一个数字范围。 如果你着急了解，这里有一个方法可以帮助你获得范围： const arrayRange = (start, stop, step) =>     Array.from(     { length: (stop - start) / step + 1 },     (value, index) ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/javascript-range-create-an-array-of-numbers-with-the-from-method/</link>
                <guid isPermaLink="false">63ac3e52f490ad07436268ac</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Miya Liu ]]>
                </dc:creator>
                <pubDate>Tue, 20 Dec 2022 14:22:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/12/pexels-damon-hall-1705254.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p data-test-label="translation-intro">
        <strong>原文：</strong> <a href="https://www.freecodecamp.org/news/javascript-range-create-an-array-of-numbers-with-the-from-method/" target="_blank" rel="noopener noreferrer" data-test-label="original-article-link">JavaScript Range – How to Create an Array of Numbers with .from() in JS ES6</a>
      </p><p><code>.from()</code> 方法是 JavaScript ES6 中 <code>Array</code> 对象的一个静态方法。它从一个类似数组或可迭代的对象（如 <code>map</code> 和 <code>set</code>）创建一个新的、浅拷贝的数组实例。</p><p>这个方法从任何具有长度属性的对象中返回一个数组。你可以用它来创建一个指定范围内的数字数组。</p><p>在这篇文章中，你将了解 <code>.from()</code> 静态方法是什么，它是如何工作的，以及你如何在 JavaScript 中创建一个数字范围。</p><p>如果你着急了解，这里有一个方法可以帮助你获得范围：</p><pre><code class="language-js">const arrayRange = (start, stop, step) =&gt;
    Array.from(
    { length: (stop - start) / step + 1 },
    (value, index) =&gt; start + index * step
    );

console.log(arrayRange(1, 5, 1)); // [1,2,3,4,5]
</code></pre><p>你可以继续阅读这篇短文来了解它的原理。</p><h2 id="-from-javascript-">.from() 方法如何在 JavaScript 中运行</h2><p><code>Array.from()</code> 方法从任何类似数组或可迭代对象中返回一个数组。该方法接收一个必选参数和另外两个可选参数：</p><pre><code class="language-js">// 语法
Array.from(arraylike, mapFunc, thisArg)
</code></pre><ul><li><code>arraylike</code> - 一个类数组或可迭代对象，用于转换为数组。</li><li><code>mapFunc</code> - 这是一个可选的参数。映射函数会在每个元素上被调用。</li><li><code>thisArg</code> - 这个值在执行 <code>mapFunc</code> 作为 <code>this</code> 的时候使用。它也是可选的。</li></ul><p>为了看看这是如何运行的，让我们使用 <code>Array.from()</code> 方法从一个字符串创建一个数组：</p><pre><code class="language-js">let newArray = Array.from("freeCodeCamp");

console.log(newArray); // ["f","r","e","e","C","o","d","e","C","a","m","p"]
</code></pre><p>在上面的例子中，<code>Array.from()</code> 方法返回一个字符串的数组。你也可以使用该方法从任何具有长度属性的对象中返回一个数组，该属性指定了对象中的元素数量。</p><pre><code class="language-js">let arrayLike = {0: 1, 1: 2, 2: 3, length: 3};
let newArray = Array.from(arrayLike);

console.log(newArray); // [1,2,3]
</code></pre><p>你也可以引入映射函数，为每个元素调用。例如，如果你想操作每个数组项，也许是将每个项与一个特定的数字相乘：</p><pre><code class="language-js">let arrayLike = {0: 1, 1: 2, 2: 3, length: 3};
let newArray = Array.from(arrayLike, x =&gt; x * 2);

console.log(newArray); // [2,4,6]
</code></pre><p><strong>注意：</strong><code>.from()</code> 是一个静态方法，这就是为什么它使用数组类的名称。你只能把它当作 <code>Array.from()</code> 来使用，而不是 <code>myArray.from()</code>，其中 <code>myArray</code> 是一个数组。它将返回未定义。</p><h2 id="-from-">如何用 .from() 方法创建一个数字序列</h2><p><code>Array.from()</code> 方法使你有可能使用映射函数创建一个数字序列：</p><pre><code class="language-js">let newArray = Array.from({ length: 7 }, (value, index) =&gt; index);

console.log(newArray); // [0,1,2,3,4,5,6]
</code></pre><p>上面的方法创建了一个由 7 个元素组成的数组，默认初始化为 <code>undefined</code>。但是使用映射函数，现在使用的是索引值而不是其实际值 undefined。</p><p>如果你使用它的实际值，你将得到一个 7 个元素的数组（基于长度），值为 undefined：</p><pre><code class="language-js">let newArray = Array.from({ length: 7 }, (value, index) =&gt; value);

console.log(newArray); 
// 返回
[undefined,undefined,undefined,undefined,undefined,undefined,undefined]
</code></pre><h2 id="-from--1">如何用 .from 方法创建一个数字范围</h2><p>你现在知道如何用一个数字序列创建一个数组。但是当你创建一个范围时，你希望这些数字从一个指定的值开始，在一个指定的值结束。例如，在 4 和 8 的范围内的数字将是 4、5、6、7、8。</p><p>你还可以指定你想要一个指定范围内的奇数或偶数的数组。所有这些都可以通过 <code>Array.from()</code> 方法实现。</p><pre><code class="language-js">const arrayRange = (start, stop, step) =&gt;
    Array.from(
    { length: (stop - start) / step + 1 },
    (value, index) =&gt; start + index * step
    );
</code></pre><p>在上面的代码中，类似数组的对象的长度是通过从范围内的第一个数字减去最后一个数字，然后除以步长加一来定义的。这将给出数组中元素的确切数量。</p><p>在映射函数中，起始数被添加到每个元素的索引中（记住，该值总是未定义的），并乘以步长值。这个映射函数为每个元素运行，帮助计算每个元素的值。</p><p>让我们用几个例子试试这个方法：</p><pre><code class="language-js">// 产生从范围 2 到 7 的数字
let range = arrayRange(2, 7, 1);
console.log(range); // [2,3,4,5,6,7]

// 产生从范围 2 到 7 的偶数
let evenRange = arrayRange(2, 7, 2);
console.log(evenRange); // [2,4,6]

// 产生从范围 1 到 5 的奇数
let oddRange = arrayRange(1, 5, 2);
console.log(oddRange); // [1,3,5]
</code></pre><h2 id="-"><strong>总结</strong></h2><p>在这篇文章中，你学习了如何用 <code>Array.from()</code> 方法创建一个数字数组，你还学习了 <code>Array.from()</code> 方法的工作原理。</p><p>请记住，在 JavaScript 中还有其他选择来创建数字范围——我们在本教程中只关注了 <code>.from()</code>。</p><p>祝你编码愉快！</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 如何在 JavaScript 中声明一个数组——在 JS 中创建一个数组 ]]>
                </title>
                <description>
                    <![CDATA[ 在 JavaScript 中，数组是最常用的数据类型之一。它在一个变量中存储多个值和元素。 这些值可以是任何数据类型——意味着你可以在一个变量中存储字符串、数字、布尔值和其他数据类型。 在 JavaScript 中，有两种标准的方法来声明数组。它们是通过数组构造函数或字面量。 下面是两种方式声明数组： // 使用构造函数 let array = new array("John Doe", 24, true); // 使用字面量 let array = ["John Doe", 24, true]; 你可以继续阅读这篇文章，以正确理解这些方法以及它们的一些其他有趣的选项。 如何用字面量声明一个数组 这是创建数组的最流行和最简单的方法。它是一种更简短、更清晰的声明数组的方法。 用字面量声明一个数组，你只需用空括号定义一个新的数组，像这样： let myArray = []; 你要把所有的元素放在方括号内，用逗号把每个项目或元素分开。 let myArray = ["John Doe", 24, true]; 数组是零索引的，这意味着你可以从零开始访问每个元素或 ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/how-to-declare-an-array-in-javascript-creating-an-array-in-js/</link>
                <guid isPermaLink="false">6387247c832e3f078176385f</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chengjun.L ]]>
                </dc:creator>
                <pubDate>Wed, 30 Nov 2022 05:32:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/11/cover-template--2-.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p data-test-label="translation-intro">
        <strong>原文：</strong> <a href="https://www.freecodecamp.org/news/how-to-declare-an-array-in-javascript-creating-an-array-in-js/" target="_blank" rel="noopener noreferrer" data-test-label="original-article-link">How to Declare an Array in JavaScript – Creating an Array in JS</a>
      </p><p>在 JavaScript 中，数组是最常用的数据类型之一。它在一个变量中存储多个值和元素。</p><p>这些值可以是任何数据类型——意味着你可以在一个变量中存储字符串、数字、布尔值和其他数据类型。</p><p>在 JavaScript 中，有两种标准的方法来声明数组。它们是通过数组构造函数或字面量。</p><p>下面是两种方式声明数组：</p><pre><code class="language-js">// 使用构造函数
let array = new array("John Doe", 24, true);

// 使用字面量
let array = ["John Doe", 24, true];
</code></pre><p>你可以继续阅读这篇文章，以正确理解这些方法以及它们的一些其他有趣的选项。</p><h2 id="-">如何用字面量声明一个数组</h2><p>这是创建数组的最流行和最简单的方法。它是一种更简短、更清晰的声明数组的方法。</p><p>用字面量声明一个数组，你只需用空括号定义一个新的数组，像这样：</p><pre><code class="language-js">let myArray = [];
</code></pre><p>你要把所有的元素放在方括号内，用逗号把每个项目或元素分开。</p><pre><code class="language-js">let myArray = ["John Doe", 24, true];
</code></pre><p>数组是零索引的，这意味着你可以从零开始访问每个元素或输出整个数组。</p><pre><code class="language-js">console.log(myArray[0]); // 'John Doe'
console.log(myArray[2]); // true
console.log(myArray); // ['John Doe', 24, true]
</code></pre><h2 id="--1">如何用数组构造函数声明一个数组</h2><p>你也可以使用数组构造函数来创建或声明一个数组。用 <code>Array()</code> 构造函数声明一个数组有很多技术上的问题。</p><p>就像你可以用字面量在一个变量中存储不同数据类型的多个值一样，你也可以用数组构造函数做同样的事情。</p><pre><code class="language-js">let myArray = new Array();
console.log(myArray); // []
</code></pre><p>上述代码将创建一个新的空数组。你可以在新数组中添加数值，方法是将它们放在括号中，用逗号隔开。</p><pre><code class="language-js">let myArray = new Array("John Doe", 24, true);
</code></pre><p>就像你之前学到的那样，你可以使用其索引号来访问每个值，索引号从零（0）开始。</p><pre><code class="language-js">console.log(myArray[0]); // 'John Doe'
console.log(myArray[2]); // true
console.log(myArray); // ['John Doe', 24, true]
</code></pre><p>当用构造函数声明数组时，必须牢记以下几点。</p><ul><li>当你向数组构造函数传递一个数字时，它将用你输入的空值的数量来填充数组。</li></ul><pre><code class="language-js">let myArray = new Array(4);
console.log(myArray); // [,,,]
</code></pre><p>但当你传递一个单一的字符串或任何其他数据类型时，它正常运行。</p><pre><code class="language-js">let myArray = new Array(true);
console.log(myArray); // [true]
</code></pre><ul><li>并非一定要添加 <code>new</code>，因为 <code>Array()</code> 和 <code>new Array()</code> 都是执行相同的任务。</li></ul><pre><code class="language-js">let myArray = Array("John Doe", 24, true);
</code></pre><h2 id="--2"><strong>小结</strong></h2><p>在这篇文章中，你已经学会了如何在 JavaScript 中声明一个数组。重要的是要知道，不是一定要使用构造函数，因为它比字面量要复杂得多。</p><p>你可以在文章《<strong><a href="https://www.freecodecamp.org/chinese/news/how-to-create-an-array-in-javascript/">JavaScript 数组——如何在 JavaScript 中创建数组</a>》</strong>中了解更多信息。</p><p>祝你编码愉快！</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 如何在 JavaScript 中交换两个数组元素 ]]>
                </title>
                <description>
                    <![CDATA[ 当你在处理数组时，有时你需要在 JavaScript 中交换数组中的两个元素。 也许你正在研究一个算法问题，比如气泡排序算法，你需要比较两个值，然后在条件为真时交换它们。 除此之外，许多其他情况可能需要你交换数组元素。 如果你还不明白我说的“交换”是什么意思，这里有一个例子。假设你有一个数字数组，你想把索引 1 的元素 -2 和索引 0 的元素 12 互换，如下图所示： 如果你还不熟悉 JS 是如何做这些事情的，在 JavaScript 中实现这一点可能会让你感到困惑。你可能也在寻找更好的方法来处理这个问题。 这篇文章将教你三种方法：使用临时变量、解构赋值和使用 splice() 数组方法。 如何用一个临时变量来交换两个数组元素 为了交换元素，你可以使用一个临时变量并经过三个步骤。 第一步是创建一个临时变量来保存第一个元素的值。第二步是将第一个元素的值设置为第二个元素的值。第三步是将第二个元素的值设置为临时变量中的值。 let myArray = [12, -2, 55, 68, 80]; const temp = myArray[0]; myArray[0] = m ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/swap-two-array-elements-in-javascript/</link>
                <guid isPermaLink="false">6141c960b201730648bda06d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Miya Liu ]]>
                </dc:creator>
                <pubDate>Thu, 06 Oct 2022 04:19:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/10/clement-helardot-95YRwf6CNw8-unsplash.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p data-test-label="translation-intro">
        <strong>原文：</strong> <a href="https://www.freecodecamp.org/news/swap-two-array-elements-in-javascript/" target="_blank" rel="noopener noreferrer" data-test-label="original-article-link">How to Swap Two Array Elements in JavaScript – Switch Elements in JS</a>
      </p><p>当你在处理数组时，有时你需要在 JavaScript 中交换数组中的两个元素。</p><p>也许你正在研究一个算法问题，比如气泡排序算法，你需要比较两个值，然后在条件为真时交换它们。</p><p>除此之外，许多其他情况可能需要你交换数组元素。</p><p>如果你还不明白我说的“交换”是什么意思，这里有一个例子。假设你有一个数字数组，你想把索引 <code>1</code> 的元素 <strong>-2</strong> 和索引 <code>0</code> 的元素 <strong>12</strong> 互换，如下图所示：</p><figure class="kg-card kg-image-card"><img src="https://paper-attachments.dropbox.com/s_B08002E277AA9EEDFC6B2A9D153D5485AA9F9B4567270177E695FBE6032A1880_1664460747763_Untitled.drawio+14.png" class="kg-image" alt="s_B08002E277AA9EEDFC6B2A9D153D5485AA9F9B4567270177E695FBE6032A1880_1664460747763_Untitled.drawio+14" width="600" height="400" loading="lazy"></figure><p>如果你还不熟悉 JS 是如何做这些事情的，在 JavaScript 中实现这一点可能会让你感到困惑。你可能也在寻找更好的方法来处理这个问题。</p><p>这篇文章将教你三种方法：使用临时变量、解构赋值和使用 <code>splice()</code> 数组方法。</p><h2 id="-">如何用一个临时变量来交换两个数组元素</h2><p>为了交换元素，你可以使用一个临时变量并经过三个步骤。</p><p>第一步是创建一个临时变量来保存第一个元素的值。第二步是将第一个元素的值设置为第二个元素的值。第三步是将第二个元素的值设置为临时变量中的值。</p><pre><code class="language-js">let myArray = [12, -2, 55, 68, 80];

const temp = myArray[0];
myArray[0] = myArray[1];
myArray[1] = temp;

console.log(myArray); // [-2,12,55,68,80]
</code></pre><p>你也可以创建一个可重复使用的函数来处理这个问题，你可以指定数组和你希望交换的两个索引。</p><pre><code class="language-js">const swapElements = (array, index1, index2) =&gt; {
    let temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
};

let myArray = [12, -2, 55, 68, 80];
swapElements(myArray, 0, 1);
console.log(myArray); // [-2,12,55,68,80]
</code></pre><h2 id="--1">如何通过解构赋值交换两个数组元素</h2><p>一个更好的交换数组元素的方法是解构赋值，因为它只需一行代码就能完成工作。</p><p>你只需创建一个新的数组，其中包含按特定顺序排列的两个元素，然后将其分配给一个新的数组，其中包含按相反顺序排列的两个元素。</p><pre><code class="language-js">let myArray = [12, -2, 55, 68, 80];

[myArray[0], myArray[1]] = [myArray[1], myArray[0]];

console.log(myArray); // [-2,12,55,68,80]
</code></pre><p>你也可以创建一个可重复使用的函数来处理这个问题，你可以指定数组和你希望交换的两个索引。</p><pre><code class="language-js">const swapElements = (array, index1, index2) =&gt; {
    [myArray[index1], myArray[index2]] = [myArray[index2], myArray[index1]];
};

let myArray = [12, -2, 55, 68, 80];
swapElements(myArray, 0, 1);
console.log(myArray); // [-2,12,55,68,80]
</code></pre><h2 id="-splice-">如何用 Splice() 方法交换两个数组元素</h2><p>最后，你可以使用 <code>splice()</code> 数组方法。你可以用这个方法从一个数组中移除一个或多个元素，然后用任何指定的元素替换这些元素。</p><pre><code class="language-js">// 语法
array.splice(index, howmany, element1, ....., elementX)
</code></pre><p>例如，如果你有一个数组，你想删除一个特定的元素，你将指定它的 <code>id</code> 和想删除的元素的数量。在我们的例子中，这两个值是 1。</p><pre><code class="language-js">let myArray = [12, -2, 55, 68, 80];

myArray.splice(1, 1);
console.log(myArray); // 12,55,68,80]
</code></pre><p>另外，如果你想用另一个元素替换掉被删除的元素，你的代码会是这样的：</p><pre><code class="language-js">let myArray = [12, -2, 55, 68, 80];

myArray.splice(1, 1, 32);
console.log(myArray); // [12,32,55,68,80]
</code></pre><p>但如果你想交换两个元素，代码应该是这样：</p><pre><code class="language-js">let myArray = [12, -2, 55, 68, 80];

myArray[0] = myArray.splice(1, 1, myArray[0])[0];

console.log(myArray); // [-2,12,55,68,80]
</code></pre><p>你也可以创建一个可重复使用的函数来处理这个问题，你可以指定数组和希望交换的两个索引。</p><pre><code class="language-js">const swapElements = (array, index1, index2) =&gt; {
    myArray[index1] = myArray.splice(index2, 1, myArray[index1])[0];
};

let myArray = [12, -2, 55, 68, 80];
swapElements(myArray, 0, 1);
console.log(myArray); // [-2,12,55,68,80]
</code></pre><h2 id="--2"><strong>小结</strong></h2><p>在这篇文章中，你学习了在 JavaScript 中交换数组元素的三种方法。</p><p>你可以使用任何方法，但最好是使用 ES6 的解构赋值方法，因为它更容易被大家理解和使用。</p><p>祝你编程愉快!</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 如何在 JavaScript 中循环遍历数组 ]]>
                </title>
                <description>
                    <![CDATA[ 数组是一个变量存储不同数据类型的元素。我们可以通过单个变量访问数组。 它是一个有序的值列表，每个值是一个元素，可以通过索引访问。 知道这些单个变量包含元素列表，你可能希望创建这些元素的列表，以便你可以使用它们执行单个功能等等。这就是循环发挥作用的地方。 JavaScript 中的循环是什么 循环是一种计算机程序，它允许我们将特定操作重复预定次数，而无需单独编写该操作。 例如，如果我们有一个数组，想要输出数组中的每个元素，我们可以简单地循环并执行一次该操作，而不是使用索引号一个一个地这样做。 在 JavaScript 中有很多方法可以循环遍历数组。在本文中，我们将介绍最常用的方法，以便你学习不同的方法并了解它们的工作原理。 我们将在本文中使用以下数组： const scores = [22, 54, 76, 92, 43, 33]; 如何在 JavaScript 中使用 While 循环遍历数组 你可以使用 while 循环来评估括在括号 () 中的条件。如果条件为 true，则执行 while 循环内的代码。如果为 false，则终止循环。 如果我们想遍历一个数组， ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/how-to-loop-through-an-array-in-javascript-js-iterate-tutorial/</link>
                <guid isPermaLink="false">630c9c26aeb66407f67d14a2</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Miya Liu ]]>
                </dc:creator>
                <pubDate>Mon, 22 Aug 2022 01:09:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/08/jamie-street-vcn2ndJ5LwE-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p data-test-label="translation-intro">
        <strong>原文：</strong> <a href="https://www.freecodecamp.org/news/how-to-loop-through-an-array-in-javascript-js-iterate-tutorial/" target="_blank" rel="noopener noreferrer" data-test-label="original-article-link">How to Loop Through an Array in JavaScript – JS Iterate Tutorial</a>
      </p><p>数组是一个变量存储不同数据类型的元素。我们可以通过单个变量访问数组。</p><p>它是一个有序的值列表，每个值是一个元素，可以通过索引访问。</p><p>知道这些单个变量包含元素列表，你可能希望创建这些元素的列表，以便你可以使用它们执行单个功能等等。这就是循环发挥作用的地方。</p><h2 id="javascript-">JavaScript 中的循环是什么</h2><p>循环是一种计算机程序，它允许我们将特定操作重复预定次数，而无需单独编写该操作。</p><p>例如，如果我们有一个数组，想要输出数组中的每个元素，我们可以简单地循环并执行一次该操作，而不是使用索引号一个一个地这样做。</p><p>在 JavaScript 中有很多方法可以循环遍历数组。在本文中，我们将介绍最常用的方法，以便你学习不同的方法并了解它们的工作原理。</p><p>我们将在本文中使用以下数组：</p><pre><code class="language-js">const scores = [22, 54, 76, 92, 43, 33];
</code></pre><h2 id="-javascript-while-">如何在 JavaScript 中使用 While 循环遍历数组</h2><p>你可以使用 <code>while</code> 循环来评估括在括号 <code>()</code> 中的条件。如果条件为 <code>true</code>，则执行 <code>while</code> 循环内的代码。如果为 <code>false</code>，则终止循环。</p><p>如果我们想遍历一个数组，可以使用 <code>length</code> 属性来指定循环应该一直持续到我们到达数组的最后一个元素。</p><p>现在让我们使用 <code>while</code> 循环方法来循环遍历数组：</p><pre><code class="language-js">let i = 0;

while (i &lt; scores.length) {
    console.log(scores[i]);
    i++;
}
</code></pre><p>这将一个接一个地返回我们数组中的每个元素：</p><pre><code class="language-bash">22
54
76
92
43
33
</code></pre><p>在上面的循环中，我们首先初始化了索引号，使其从 <code>0</code> 开始。然后这个数字会不断增加并输出每个元素，直到我们设置的条件返回 <code>false</code>，说明我们已经到了数组的末尾。当 <code>i = 6</code> 时，将不再执行条件，因为数组的最后一个索引是 <code>5</code>。</p><h2 id="-javascript-do-while-">如何在 JavaScript 中使用 do…while 循环遍历数组</h2><p><code>do...while</code> 循环与 <code>while</code> 循环几乎相同，只是它先执行主体，然后再评估后续执行的条件。这意味着循环的主体总是至少执行一次。</p><p>让我们用 <code>do...while</code> 循环执行相同的循环，看看它是如何工作的：</p><pre><code>let i = 0;

do {
    console.log(scores[i]);
    i++;
} while (i &lt; scores.length);
</code></pre><p>这将返回我们数组中的每个元素：</p><pre><code class="language-bash">22
54
76
92
43
33
</code></pre><p>如前所述，这将始终在评估任何条件集之前运行一次。例如，如果我们将索引 <code>i</code> 设置为 <code>6</code>，并且它不再小于 <code>score.length</code>，则循环体将在检查条件之前首先运行：</p><pre><code class="language-js">let i = 6;

do {
    console.log(scores[i]);
    i++;
} while (i &lt; scores.length);
</code></pre><p>这将返回 <code>undefined</code>，因为我们在数组中没有索引为 <code>6</code> 的元素，但你可以看到它在停止之前运行了一次。</p><h2 id="-javascript-for-">如何在 JavaScript 中使用 for 循环遍历数组</h2><p><code>for</code> 循环是一个迭代语句，它检查某些条件，然后只要满足这些条件就重复执行一段代码。</p><p>使用 <code>for</code> 循环方法时，我们不需要先初始化索引，因为初始化、条件、迭代都在括号中处理，如下所示：</p><pre><code class="language-js">for (let i = 0; i &lt; scores.length; i++) {
    console.log(scores[i]);
}
</code></pre><p>这将像其他方法一样返回所有元素：</p><pre><code class="language-bash">22
54
76
92
43
33
</code></pre><h2 id="-javascript-for-in-">如何在 JavaScript 中使用 for...in 循环遍历数组</h2><p><code>for...in</code> 循环是一种更简单的遍历数组的方法，因为它为我们提供了键，我们现在可以使用该键以这种方式从数组中获取值：</p><pre><code class="language-js">for (i in scores) {
    console.log(scores[i]);
}
</code></pre><p>这将输出我们数组中的所有元素：</p><pre><code class="language-bash">22
54
76
92
43
33</code></pre><h2 id="-javascript-for-of-">如何在 JavaScript 中使用 for...of 循环遍历数组</h2><p><code>for...of</code> 循环遍历可迭代对象，例如数组、集合、映射、字符串等。它与 <code>for...in</code> 循环具有相同的语法，但它不是获取键，而是获取元素本身。</p><p>这是循环数组的最简单方法之一，并在 JavaScript ES6 的更高版本中引入。</p><pre><code>for (score of scores) {
    console.log(score);
}
</code></pre><p>这将获取数组的每个元素，我们不再需要使用索引来获取数组的每个元素：</p><pre><code class="language-bash">22
54
76
92
43
33
</code></pre><h2 id="-javascript-foreach-">如何在 JavaScript 中使用 forEach 循环遍历数组</h2><p>数组方法 <code>forEach()</code> 循环遍历任何数组，按索引升序对每个数组元素执行一次提供的函数。此函数被称为回调函数。</p><p>这是一种更高级的方法，它可以做的不仅仅是简单地遍历每个元素，你也可以使用它以这种方式循环：</p><pre><code class="language-js">scores.forEach((score) =&gt; {
    console.log(score);
});
</code></pre><p>你可以这样写成一行：</p><pre><code class="language-js">scores.forEach((score) =&gt; console.log(score));
</code></pre><p>这将为我们提供与所有先前方法相同的输出：</p><pre><code class="language-bash">22
54
76
92
43
33
</code></pre><h2 id="-"><strong>总结</strong></h2><p>在本文中，我们研究了六种不同/标准的遍历数组的方法。</p><p>了解所有这些方法，然后确定哪种方法更适合你、更易于使用且更易于阅读，这一点非常重要。</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 在 JavaScript 中如何使用 flat() 和 flatMap() 方法展平数组 ]]>
                </title>
                <description>
                    <![CDATA[ 原文：How to Use the flat() and flatMap() Methods to Flatten Arrays in JavaScript [https://www.freecodecamp.org/news/flat-and-flatmap-javascript-array-methods/] ，作者：Kenechukwu Nwobodo [https://www.freecodecamp.org/news/author/kene10/] 在本文中，我将解释如何使用 ES2019（EcmaScript 2019）中引入的新数组方法——flat() 和 flatMap() 。你可以使用这些方法来展平数组。 这些方法非常有用且易于使用。在你的下一个项目中使用这些方法真的很酷。喝杯咖啡，让我们开始学习吧。 前提 你应该熟悉 JavaScript 中数组的概念，然后才能学习本教程。 什么是数组 数组对象是一种数据结构，在不同的编程语言中用于存储不同的数据集合。 JavaScript 中的数组示例 const array = [1, 2, 3, true, null ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/flat-and-flatmap-javascript-array-methods/</link>
                <guid isPermaLink="false">62ea31d98d13aa0845c63866</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chengjun.L ]]>
                </dc:creator>
                <pubDate>Wed, 03 Aug 2022 08:56:12 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/08/js-map-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>原文：<a href="https://www.freecodecamp.org/news/flat-and-flatmap-javascript-array-methods/">How to Use the flat() and flatMap() Methods to Flatten Arrays in JavaScript</a>，作者：<a href="https://www.freecodecamp.org/news/author/kene10/">Kenechukwu Nwobodo</a></p><p>在本文中，我将解释如何使用 ES2019（EcmaScript 2019）中引入的新数组方法——<code>flat()</code> 和 <code>flatMap()</code>。你可以使用这些方法来展平数组。</p><p>这些方法非常有用且易于使用。在你的下一个项目中使用这些方法真的很酷。喝杯咖啡，让我们开始学习吧。</p><h2 id="-">前提</h2><p>你应该熟悉 JavaScript 中数组的概念，然后才能学习本教程。</p><h2 id="--1">什么是数组</h2><p>数组对象是一种数据结构，在不同的编程语言中用于存储不同的数据集合。</p><h3 id="javascript-"><strong>JavaScript 中的数组示例</strong></h3><pre><code class="language-javascript">const array = [1, 2, 3, true, null, undefined];

console.log(array);

// 期待的输出
1, 2, 3, true, null, undefined
</code></pre><p>在上面的代码中，我们分配了一个名为 <code>arr</code> 的变量，并在其中存储了不同数据类型的不同元素/数据。</p><p>第一个为 1 的元素位于索引 0 处。最后一个元素 undefined 位于索引 5 处。</p><p>不要忘记数组对象是零索引的，这意味着第一个元素从零索引开始。</p><h2 id="javascript--1">JavaScript 数组的特征</h2><ul><li><strong>数组是零索引的：</strong>这表示数组中的第一个元素位于索引 0 处。这里的索引表示位置。在 JavaScript 和其他编程语言中，我们应该使用的词是索引而不是位置。</li><li><strong>JavaScript 数组可以包含不同的数据类型：</strong>这意味着 JavaScript 数组可以包含数字、字符串、布尔值、空值等的混合。</li><li><strong>JavaScript 创建浅拷贝：</strong>这意味着你可以创建数组的不同副本——即无需更改原始数组。</li></ul><h2 id="-javascript-">新的 JavaScript 数组方法</h2><p>数组是 JavaScript 中用于存储数据的最流行的数据结构之一。</p><p>你可以使用不同的数组方法来简化操作并使你的生活更轻松。其中一些方法包括 <code>reduce()</code>、<code>filter()</code>、<code>map()</code>、<code>flat()</code>、<code>flatMap()</code> 等等。</p><p>但在本文中，我们不会讨论 JavaScript 中使用的所有数组方法。在这里，我们将讨论新的 <code>flat()</code> 和 <code>flatMap()</code> 方法，你可以使用它们将原始数组转换为新数组。</p><h2 id="-javascript-flat-">如何在 JavaScript 中使用 flat 数组方法</h2><p>你使用 <code>flat</code> 方法将原始数组转换为新数组。它通过收集数组中的子数组并将其连接到单个数组中来实现这一点。</p><p>关于此数组方法的一个重要说明是，你可以根据数组的深度将原始数组计算为另一个数组。这种方法非常有用，因为它使计算数组的操作变得更加容易。</p><h2 id="flat-">flat() 数组方法的例子</h2><h3 id="-depth-">如何设置 depth 参数</h3><pre><code class="language-js">array.flat(depth);
</code></pre><p>depth 值默认为 1，你可以将其留空。depth 值采用数字作为其数据类型。</p><h4 id="flat-1"><code><strong>flat()</strong></code><strong> 数组方法示例 1</strong></h4><p><code>array.flat(1)</code> 等同于 <code>array.flat()</code>。</p><p><code>array.flat(2);</code></p><p>上面的 depth 值是 2。</p><pre><code class="language-javascript">const arr = ["mon", "tues", ["wed", "thurs", ["fri", "sat"]], "sun"] ;

console.log(arr.flat());

// 期待的输出
["mon", "tues", "wed", "thurs", Array ["fri", "sat"], "sun"];
</code></pre><p>那么这段代码发生了什么？</p><p>首先，该数组包含两个子数组，它们是 <code>["wed", "thurs", ["fri", "sat"]]</code>。</p><p>我们在名为 <code>arr</code> 的数组上使用 <code>flat()</code> 方法连接第一个子数组，因为我们没有在 <code>flat()</code> 方法中指定 depth 值。回想一下，默认 depth 值为 1。</p><p>所以你可以猜到如果 depth 值为 2，数组对象会是什么，对吧？</p><h4 id="flat-2"><code><strong>flat()</strong></code><strong> 数组方法示例 2</strong></h4><pre><code class="language-javascript">const arr = [1, 2, [3, 4, 5], 6, 7];

console.log(arr.flat());

// 期待的输出
[1, 2, 3, 4, 5, 6, 7]
</code></pre><p>在上面的代码中，数组包含一个子数组，即 <code>[3, 4, 5]</code>。</p><p>我们在名为 <code>arr</code> 的数组上使用 <code>flat()</code> 方法将两个数组连接在一起成为一个数组。</p><h4 id="flat-3"><code><strong>flat()</strong></code><strong> 数组方法示例 3</strong></h4><pre><code class="language-javascript">//depth 2 example 
const arr2 = [[[1, 2], 3, 4, 5]] ;

console.log(arr2.flat(2));

// 期待的输出
[1, 2, 3, 4, 5]
</code></pre><p>在上面的代码中，名为 <code>arr2</code> 的数组包含两个子数组。</p><p>我们在 <code>arr2</code> 上使用 <code>flat()</code> 方法将两个数组连接成一个数组，因为在 <code>flat(2)</code> 方法中使用了 depth 值 2。快速浏览一下上面的 depth 值的作用。</p><p>数组方法是递归连接数组中元素的好方法。</p><h2 id="-javascript-flatmap-">如何在 JavaScript 中使用 flatMap 数组方法</h2><p><code>flatMap()</code> 方法使用 <code>map()</code> 和 <code>flat()</code> 方法的组合来执行操作。</p><p><code>flatMap()</code> 循环遍历数组的元素，并将元素连接到一个级别。 <code>flatMap()</code> 接受一个回调函数，该函数接受原始数组的当前元素作为参数。</p><h3 id="flatmap-"><strong><code>flatMap()</code> 数组方法示例</strong></h3><pre><code class="language-javascript">const arr3 = [1, 2, [4, 5], 6, 7, [8]] ;

console.log(arr3.flatMap((element) =&gt; element)); 

// 期待的输出
[1, 2, 4, 5, 6, 7, 8]
</code></pre><p>在上面的代码中，名为 <code>arr3</code> 的数组包含两个不同的子数组。</p><p>我们通过传入一个回调函数 <strong>(element) =&gt; element</strong> 在数组上使用 <code>flatMap()</code> 方法，该函数循环遍历数组，然后将数组连接成一个数组。</p><p>有时你会遇到一种情况，即 depth 值大于 1，并且你决定将新数组更改为一个基本级别，然后你必须在 <code>flatMap()</code> 方法之后立即使用 <code>flat()</code> 方法。</p><h3 id="--2"><strong>这是一个例子：</strong></h3><pre><code class="language-javascript">const arr4 = [1, 2, [3, [4, 5, [6, 7]]]] ;

console.log(arr4.flatMap((element) =&gt; element).flat(2)) ;

// 期待的输出 
[1, 2, 3, 4, 5, 6, 7]

</code></pre><p>在上面的代码中，名为 <code>arr4</code> 的数组包含三个子数组。</p><p>我们通过传入一个回调函数 <strong>(element) =&gt; element</strong> 在数组上使用 <code>flatMap()</code> 方法，该函数循环遍历数组，然后连接数组。</p><p>我们使用 <code>flat(2)</code> 方法通过传入 depth 值 2 来进一步将数组连接成单个数组。</p><p>确保在不通过 <code>flat(2)</code> 方法的情况下练习上面的示例并查看差异。</p><p>这就是你开始使用这两种新数组方法所需的全部内容。</p><h2 id="--3"><strong>小结</strong></h2><p>在本文中，我简要讨论了数组是什么以及它们在 JavaScript 中的用处。然后我们了解了 ECMAScript 2019 中引入的两个新的重要数组方法，它们允许你将原始数组更改为新数组。</p><p>这些新的数组方法是 <code>flat()</code> 和 <code>flatMap()</code> 方法。</p><p>你使用 <code>flat()</code> 方法将子数组递归地连接到单个数组中。<code>flat()</code> 方法将 depth 值作为其参数，该参数是可选的，具体取决于你希望展平（连接）的数组的深度。<code>flat()</code> 方法默认采用 1 作为深度。</p><p>另一方面，<code>flatMap()</code> 的工作原理基本相同，只是它是 <code>map()</code> 和 <code>flat()</code> 方法的组合。 <code>flatMap()</code> 循环遍历数组中的元素并连接元素。</p><p>当你将原始数组更改为新数组时，这两种新方法都很有用。它们值得你在下一个大项目或小项目中尝试。</p><h3 id="--4"><strong>参考资料：</strong></h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap">MDN 上关于 flatMap() 的介绍</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat">MDN 上关于 flat() 的介绍</a></li></ul> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 使用 JavaScript Array.includes() 方法检查项目是否在数组中 ]]>
                </title>
                <description>
                    <![CDATA[ 原文：Check if an Item is in an Array in JavaScript – JS Contains with Array.includes() [https://www.freecodecamp.org/news/check-if-an-item-is-in-an-array-in-javascript-js-contains-with-array-includes/] ，作者：Ihechikara Vincent Abba [https://www.freecodecamp.org/news/author/ihechikara/] 你可以使用 JavaScript 中的 includes() 方法来检查一个项目是否存在于数组中。你还可以使用它来检查字符串中是否存在子字符串。 如果在数组/字符串中找到该项目，则返回 true；如果该项目不存在，则返回 false。 在本文中，你将了解如何使用 JavaScript 中的 includes() 方法来检查项目是否在数组中，以及字符串中是否存在子字符串。 在 JavaScript 中如何使用 Array.i ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/check-if-an-item-is-in-an-array-in-javascript-js-contains-with-array-includes/</link>
                <guid isPermaLink="false">62e201d58d13aa0845c63096</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Miya Liu ]]>
                </dc:creator>
                <pubDate>Mon, 25 Jul 2022 03:20:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/07/pankaj-patel-1IW4HQuauSU-unsplash.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>原文：<a href="https://www.freecodecamp.org/news/check-if-an-item-is-in-an-array-in-javascript-js-contains-with-array-includes/">Check if an Item is in an Array in JavaScript – JS Contains with Array.includes()</a>，作者：<a href="https://www.freecodecamp.org/news/author/ihechikara/">Ihechikara Vincent Abba</a></p><p>你可以使用 JavaScript 中的 <code>includes()</code> 方法来检查一个项目是否存在于数组中。你还可以使用它来检查字符串中是否存在子字符串。</p><p>如果在数组/字符串中找到该项目，则返回 <code>true</code>；如果该项目不存在，则返回 <code>false</code>。</p><p>在本文中，你将了解如何使用 JavaScript 中的 <code>includes()</code> 方法来检查项目是否在数组中，以及字符串中是否存在子字符串。</p><h2 id="-javascript-array-includes-"><strong>在 JavaScript 中如何使用 <code>Array.includes()</code> 来检查项目是否在数组中</strong></h2><p>下面是使用 <code>includes()</code> 方法检查项目是否在数组中的语法：</p><pre><code class="language-txt">array.includes(item, fromIndex)</code></pre><p>让我们分解上面的语法：</p><p><code>array</code> 表示将被搜索以检查项目是否存在的数组的名称。</p><p><code>includes()</code> 方法接受两个参数——<code>item</code> 和 <code>fromIndex</code>。</p><ul><li><code>item</code> 是你正在搜索的特定项目。</li><li><code>fromIndex</code> 是一个可选参数，指定开始搜索的索引。如果不包含此参数，则默认索引将设置为 0（第一个索引）。</li></ul><p>下面是一些示例，展示如何使用 <code>includes()</code> 方法检查数组中是否存在项目：</p><pre><code class="language-javascript">const nums = [ 1, 3, 5, 7];
console.log(nums.includes(3));
// true</code></pre><p>在上面的示例中，我们创建了一个名为 <code>nums</code> 的数组，其中包含四个数字——1、3、5、7。</p><p>使用点表示法，我们将 <code>includes()</code> 方法附加到 <code>nums</code> 数组。</p><p>在 <code>includes()</code> 方法的参数中，我们传入了 3，这是我们要搜索的项目。</p><p>我们返回了 <code>true</code>，因为 <code>nums</code> 数组中存在 3。</p><p>让我们尝试搜索数组中不存在的数字。</p><pre><code class="language-javascript">const nums = [ 1, 3, 5, 7];
console.log(nums.includes(8));
// false
</code></pre><p>正如预期的那样，我们在上面的示例中返回了 <code>false</code>，因为 8 不是 <code>nums</code> 数组中的项目。</p><h2 id="-javascript-array-includes--1">在 JavaScript 中如何使用 Array.includes() 从指定索引开始检查项目是否在数组中</h2><p>在上一节中，我们看到了如何在不使用 <code>includes()</code> 方法中的第二个参数的情况下检查一个项目是否存在于数组中。</p><p>提醒一下，第二个参数用于指定在数组中搜索项目时的起始索引。</p><p>数组的索引从 0 开始。所以第一项是 0，第二项是 1，第三项是 2，以此类推。</p><p>下面是一个例子来展示我们如何使用 <code>includes()</code> 方法的第二个参数：</p><pre><code class="language-javascript">const nums = [ 1, 3, 5, 7];
console.log(nums.includes(3,2));
// false</code></pre><p>即使我们在数组中有 3 这个项目，上面的示例仍返回 <code>false</code>，原因如下：</p><p>使用第二个参数，我们告诉 <code>include()</code> 方法从索引 2 开始搜索数字 3：<code>nums.includes(3,2)</code>。</p><p>这是数组： [ 1, 3, 5, 7]<br>索引 0 = 1<br>索引 1 = 3<br>索引 2 = 5<br>索引 3 = 7</p><p>所以从第二个索引 5 开始，我们只有 5 和 7 ([5,7]) 需要搜索。这就是为什么从索引 2 搜索 3 返回 <code>false</code> 的原因。</p><p>如果你更改索引以从 1 开始搜索，那么将返回 <code>true</code>，因为可以在该范围内找到 3。</p><pre><code class="language-javascript">const nums = [ 1, 3, 5, 7];
console.log(nums.includes(3,1));
// true</code></pre><h2 id="-javascript-includes-">在 JavaScript 中如何使用 includes() 方法检查子字符串是否在字符串中</h2><p>与前面的示例类似，你必须使用点表示法将 <code>include()</code> 方法附加到要搜索的字符串的名称上。</p><p>语法如下所示：</p><pre><code class="language-txt">string.includes(substring, fromIndex)</code></pre><p>这是一个例子：</p><pre><code class="language-javascript">const bio = "I am a web developer";
console.log(bio.includes("web"));
// true</code></pre><p>在上面的示例中，<code>bio</code> 变量的值为 “I am a web developer”。</p><p>使用 <code>includes()</code> 方法，我们搜索了子字符串 “web”。</p><p>我们返回了 <code>true</code>，因为 “web” 在 <code>bio</code> 字符串中。</p><p>你还可以使用第二个参数指定搜索的开始位置，但请注意字符串中的每个字符都代表一个索引，每个子字符串之间的空格也代表一个索引。</p><p>这是一个示例：</p><pre><code class="language-javascript">let bio = "I am a web developer";
console.log(bio.includes("web",9));
// false</code></pre><p>我们得到了 <code>false</code>，因为 “web” 中的索引 9 是 e。</p><p>从索引 9 开始，字符串将是 “eb developer”。字符串中不存在子字符串 “web”，因此返回 <code>false</code>。</p><h2 id="-">小结</h2><p>在本文中，我们讨论了 JavaScript 中的 <code>includes()</code> 方法。你可以使用它来检查一个项目是否存在于数组中。你还可以使用它来检查是否可以在字符串中找到子字符串。</p><p>我们看到了一些示例，这些示例解释了它用于从第一个索引开始检查数组中的项目，然后是指定索引的另一个示例。</p><p>最后，我们看到了如何使用 <code>includes()</code> 方法来检查从第一个索引和指定索引开始的字符串中是否存在子字符串。</p><p>祝你编程愉快！</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 如何使用 JavaScript String.prototype.replace() 方法 ]]>
                </title>
                <description>
                    <![CDATA[ 原文：JavaScript Replace – How to Use the String.prototype.replace() Method JS Example [https://www.freecodecamp.org/news/javascript-replace-how-to-use-the-string-prototype-replace-method-js-example/] ，作者：Kolade Chris [https://www.freecodecamp.org/news/author/kolade/] String.prototype.replace() 方法搜索第一次出现的字符串，并将其替换为指定的字符串。它在不改变原始字符串的情况下执行此操作。 此方法也适用于正则表达式，因此你正在搜索的项目可能是正则表达式。 作为替换值返回的值可能是字符串或函数。 String.prototype.replace() 方法的基本语法 const variable = variable.replace("stringToReplace", "expectedStrin ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/javascript-replace-how-to-use-the-string-prototype-replace-method-js-example/</link>
                <guid isPermaLink="false">626277a899ec7406219e7699</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Miya Liu ]]>
                </dc:creator>
                <pubDate>Fri, 22 Apr 2022 09:39:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/04/replace.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>原文：<a href="https://www.freecodecamp.org/news/javascript-replace-how-to-use-the-string-prototype-replace-method-js-example/">JavaScript Replace – How to Use the String.prototype.replace() Method JS Example</a>，作者：<a href="https://www.freecodecamp.org/news/author/kolade/">Kolade Chris</a></p><p><code>String.prototype.replace()</code> 方法搜索第一次出现的字符串，并将其替换为指定的字符串。它在不改变原始字符串的情况下执行此操作。</p><p>此方法也适用于正则表达式，因此你正在搜索的项目可能是正则表达式。</p><p>作为替换值返回的值可能是字符串或函数。</p><h2 id="string-prototype-replace-"><strong>String.prototype.replace() 方法的基本语法</strong></h2><pre><code class="language-js">const variable = variable.replace("stringToReplace", "expectedString");
</code></pre><p>你可以通过以下方式使用 <code>replace()</code> 方法：</p><ul><li>将初始字符串或字符串分配给变量</li><li>声明另一个变量</li><li>对于新变量的值，在新变量名前加上 <code>replace()</code> 方法</li><li>逗号分隔要替换的字符串和括号中的预期字符串</li></ul><h2 id="string-prototype-replace--1"><strong>String.prototype.replace() 方法使用示例</strong></h2><p>这是一个基本的示例：</p><pre><code class="language-js">const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
</code></pre><p>在上面的示例中：</p><ul><li>我声明了一个名为 <code>coding</code> 的变量，并为它赋值了字符串 “<code>I learned how to code from TV</code>”</li><li>我声明了另一个名为 <code>replacedString</code> 的变量</li><li>对于 <code>replacedString</code> 变量的值，我引入了 <code>replace()</code> 方法，并指定我想将初始变量中的 “TV” 替换为 “freeCodeCamp”。</li></ul><p>下面是一个示例，展示了 <code>replace()</code> 方法永远不会改变（更改）初始字符串：</p><pre><code class="language-js">const coding = "I learned how to code from TV";
const replacedString = coding.replace("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
console.log(coding); // Result: I learned how to code from TV
</code></pre><p>在下面的示例中，我使用正则表达式搜索匹配 “TV” 的文本并将其替换为 “freeCodeCamp”：</p><pre><code class="language-js">const coding = "I learned how to code from TV";
const replacedString = coding.replace(/TV/, "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp
</code></pre><p>由于 <code>replace()</code> 方法仅适用于字符串中某些文本第一次出现，如果你想用另一个单词完全替换字符串中的某个单词怎么办？你可以使用 <code>replaceAll()</code> 方法。</p><h2 id="-replaceall-">如何使用 replaceAll() 方法</h2><p>与 <code>replace()</code> 方法稍微相似的字符串方法是 <code>replaceAll()</code> 方法。</p><p>此方法完全替换字符串中某个单词。</p><h3 id="replaceall-"><code><strong>replaceAll()</strong></code><strong> 方法示例</strong></h3><pre><code class="language-js">const coding = "I learned how to code from TV. TV remains in my heart for life.";
const replacedString = coding.replaceAll("TV", "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp. freeCodeCamp remains in my heart for life.
</code></pre><p><code>replaceAll()</code> 方法把每次出现的 “TV” 都被替换为 “freeCodeCamp”。</p><p>使用原始的 <code>replace()</code> 方法，你可以通过使用正则表达式搜索字符串中某个单词，并将其替换为另一个单词，来实现 <code>replaceAll()</code> 的功能。</p><pre><code class="language-js">const coding = "I learned how to code from TV. TV remains in my heart for life.";
const replacedString = coding.replace(/TV/g, "freeCodeCamp");

console.log(replacedString); // Result: I learned how to code from freeCodeCamp. freeCodeCamp remains in my heart for life.
</code></pre><p>我能够使用正则表达式的 <code>g</code> 标志搜索与 “TV” 匹配的每个单词，并将其替换为 “freeCodeCamp”。</p><h2 id="-replace-">如何将函数传递给 replace() 方法</h2><p>正如我之前所说，你可以将要返回的值作为函数的替换值。</p><p>在下面的示例中，我使用 <code>replace()</code> 方法将本文的标题转换为 URL slug：</p><pre><code class="language-js">const articleTitle = "JavaScript Replace – How to Use the String.prototype.replace() Method";
const slugifyArticleTitle = articleTitle.toLowerCase().replace(/ /g, function (article) {
    return article.split(" ").join("-");
  });

console.log(slugifyArticleTitle); //Result: javascript-replace-–-how-to-use-the-string.prototype.replace()-method
</code></pre><p>在上面的脚本中：</p><ul><li>我声明了一个名为 <code>articleTitle</code> 的变量，并把这篇文章的标题赋值给它</li><li>我声明了另一个名为 <code>slugifyArticleTitle</code> 的变量，并使用 <code>toLowerCase()</code> 方法将文章标题转换为小写字母</li><li>我引入了 <code>replace()</code> 方法并用 <code>/ /g</code> 搜索每个空格</li><li>然后我将一个函数传递给 <code>replace()</code> 方法，并为其分配了一个 <code>article</code> 参数，该参数是指被转换为小写字母的字符串（文章标题）</li><li>在函数内部，返回的是将文章标题按空格进行拆分，这是通过 <code>split()</code> 方法完成的</li><li>在所有有空格的地方拆分文章标题后，我使用 <code>join()</code> 方法用连字符连接字符串中的各个字母</li></ul><h2 id="-"><strong>总结</strong></h2><p><code>String.prototype.replace()</code> 方法是一个强大的字符串方法，你可以在 JavaScript 中处理字符串时完成很多事情。</p><p>除了 <code>String.prototype.replace()</code> 方法之外，我还向你展示了如何使用 <code>String.prototype.replaceAll()</code> 方法—— <code>String.prototype.replace()</code> 方法的混合体。</p><p>你应该小心使用 <code>String.prototype.replaceAll()</code> 方法，因为某些浏览器尚不支持它。除了使用 <code>replaceAll()</code>，我还向你展示了如何通过使用正则表达式搜索特定字符串中的所有值来实现相同的功能。</p><p>如果你觉得这篇文章有帮助，请不要犹豫，与你的朋友和家人分享它。</p><p>感谢你阅读本文。</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 最常用的 JavaScript 数组方法（含代码示例） ]]>
                </title>
                <description>
                    <![CDATA[ 原文：JavaScript Array Methods Tutorial – The Most Useful Methods Explained with Examples [https://www.freecodecamp.org/news/complete-introduction-to-the-most-useful-javascript-array-methods/] ，作者：Yogesh Chavan [https://www.freecodecamp.org/news/author/yogesh/] 如果你是一个想提升自身编程能力的 JavaScript 开发者，那你应该对最常用的 ES5 和 ES6+ 的数组方法很熟悉。 这些方法能使编程变得更简单，并让你的代码看起来整洁易读。 在这篇文章中，我们将探索一些最受欢迎并被广泛使用的数组方法。让我们开始吧。 Array.forEach 方法 Array.forEach  方法的语法如下： Array.forEach(callback(currentValue [, index [, array]])[, thisAr ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/complete-introduction-to-the-most-useful-javascript-array-methods/</link>
                <guid isPermaLink="false">625e871199ec7406219e6c93</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sunny Sun ]]>
                </dc:creator>
                <pubDate>Tue, 19 Apr 2022 09:30:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/04/602b49ef0a2838549dcc6285.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>原文：<a href="https://www.freecodecamp.org/news/complete-introduction-to-the-most-useful-javascript-array-methods/">JavaScript Array Methods Tutorial – The Most Useful Methods Explained with Examples</a>，作者：<a href="https://www.freecodecamp.org/news/author/yogesh/">Yogesh Chavan</a></p><!--kg-card-begin: markdown--><p>如果你是一个想提升自身编程能力的 JavaScript 开发者，那你应该对最常用的 ES5 和 ES6+ 的数组方法很熟悉。</p>
<p>这些方法能使编程变得更简单，并让你的代码看起来整洁易读。</p>
<p>在这篇文章中，我们将探索一些最受欢迎并被广泛使用的数组方法。让我们开始吧。</p>
<h2 id="arrayforeach">Array.forEach 方法</h2>
<p><code>Array.forEach</code> 方法的语法如下：</p>
<pre><code class="language-js">Array.forEach(callback(currentValue [, index [, array]])[, thisArg]);
</code></pre>
<p><code>forEach</code> 方法为数组中的每一项执行一次给定的函数。</p>
<p>请看以下代码：</p>
<pre><code class="language-js">const months = ['January', 'February', 'March', 'April'];

months.forEach(function(month) {
  console.log(month);
});

/* output

January
February
March
April

*/
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/bGBqzOw?editors=0012">CodePen 演示</a>。</p>
<p>在这个 <code>forEach</code> 循环的回调函数中，数组中的每一项都自动作为第一个参数传到函数中。</p>
<p>与上面例子的效果相同的 for 循环代码如下：</p>
<pre><code class="language-js">const months = ['January', 'February', 'March', 'April'];

for(let i = 0; i &lt; months.length; i++) {
  console.log(months[i]);
}

/* output

January
February
March
April

*/
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/abBJXMR?editors=0012">CodePen 演示</a>。</p>
<p>要记住的一点是，这个方法不返回任何值。</p>
<p>请看以下代码：</p>
<pre><code class="language-js">const months = ['January', 'February', 'March', 'April'];
const returnedValue = months.forEach(function (month) {
  return month;
});

console.log('returnedValue: ', returnedValue); // undefined
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/PobpxGb?editors=0012">CodePen 演示</a>。</p>
<blockquote>
<p><em>注意</em> <code>_forEach_</code> <em>只用于循环数组，执行操作或者打印日志。它并不返回任何值，即使在回调函数中明确的返回一个值（这意味着上个例子中返回的值是</em> <code>undefined</code> <em>）。</em></p>
</blockquote>
<p>在上面的所有例子中，我们都只使用了回调函数的第一个参数。但回调函数还接收两个额外的参数，它们是：</p>
<ul>
<li>index - 当前迭代元素的索引</li>
<li>array - 当前循环的原始数组</li>
</ul>
<pre><code class="language-js">const months = ['January', 'February', 'March', 'April'];

months.forEach(function(month, index, array) {
  console.log(month, index, array);
});

/* output

January 0 ["January", "February", "March", "April"]
February 1 ["January", "February", "March", "April"]
March 2 ["January", "February", "March", "April"]
April 3 ["January", "February", "March", "April"]

*/
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/OJbpqJR?editors=0012">CodePen 演示</a>。</p>
<p>根据不同的需求，你会发现 <code>index</code> 和<code>array</code> 这两个参数也很有用。</p>
<h3 id="foreachfor">forEach 相比 for 循环的优点</h3>
<ul>
<li>使用 <code>forEach</code> 能让你的代码量更少，且更容易理解</li>
<li>使用 <code>forEach</code> 时，我们不需要记录数组中有多少可用元素，因此可以避免创建一个额外的计数器变量。</li>
<li>使用 <code>forEach</code> 循环更方便调试，因为循环数组没有额外的变量</li>
<li>在数组中所有元素都迭代完，<code>forEach</code> 循环会自动停止。</li>
</ul>
<h3 id="">浏览器支持</h3>
<ul>
<li>IE9 版本及以上和所有现代浏览器</li>
<li>Edge12 版本及以上</li>
</ul>
<h2 id="arraymap">Array.map 方法</h2>
<p>数组的 map 方法是所有其他方法中最有用且使用最广泛的。</p>
<p><code>Array.map</code> 方法的语法如下：</p>
<pre><code class="language-js">Array.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])
</code></pre>
<p><code>map</code> 方法为数组中的每个元素执行一次给定的函数，并且 <strong>返回一个转换过后的新数组。</strong></p>
<p>请看以下代码：</p>
<pre><code class="language-js">const months = ['January', 'February', 'March', 'April'];
const transformedArray = months.map(function (month) {
  return month.toUpperCase();
});

console.log(transformedArray); // ["JANUARY", "FEBRUARY", "MARCH", "APRIL"]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/ExNWOyr?editors=0012">CodePen 演示</a>。</p>
<p>在上面的代码中，回调函数将每个元素转化成大写并且返回。</p>
<p>与上面例子的效果相同的 for 循环代码如下：</p>
<pre><code class="language-js">const months = ['January', 'February', 'March', 'April'];
const converted = [];

for(let i = 0; i &lt; months.length; i++) {
 converted.push(months[i].toUpperCase());
};

console.log(converted); // ["JANUARY", "FEBRUARY", "MARCH", "APRIL"]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/gOLmyQQ?editors=0012">CodePen 演示</a>。</p>
<p>使用 <code>map</code> 可以避免预先创建一个单独的 <code>转换过的</code> 数组来存储转换过的元素。因此使用 <code>map</code> 可以节省储存空间，也能让代码看起来更整洁，如下：</p>
<pre><code class="language-js">const months = ['January', 'February', 'March', 'April'];

console.log(months.map(function (month) {
  return month.toUpperCase();
})); // ["JANUARY", "FEBRUARY", "MARCH", "APRIL"]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/oNYZVoX?editors=0012">CodePen 演示</a>。</p>
<p>注意 <code>map</code> 方法返回一个与原数组长度一致的新数组。</p>
<p><code>forEach</code> 与 <code>map</code> 方法的区别是 <code>forEach</code> 只用于循环，没有任何返回值。而 <code>map</code> 方法返回一个与原数组长度相同的新数组。</p>
<p>也要注意 <code>map</code> 并不改变原数组而是返回一个新的数组。</p>
<p>请看以下代码：</p>
<pre><code class="language-js">const users = [
  {
    first_name: 'Mike',
    last_name: 'Sheridan'
  },
  {
    first_name: 'Tim',
    last_name: 'Lee'
  },
  {
    first_name: 'John',
    last_name: 'Carte'
  }
];

const usersList = users.map(function (user) {
  return user.first_name + ' ' + user.last_name;
});

console.log(usersList); // ["Mike Sheridan", "Tim Lee", "John Carte"]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/LYbWaxP?editors=0012">CodePen 演示</a>。</p>
<p>这里通过使用对象数组和 <code>map</code> 方法，我们可以轻松生成一个姓和名组合的一维数组。</p>
<p>上面的代码中，我们使用 <code>+</code> 连接符连接两个值，但通常我们会使用 ES6 的模板字符串语法，如下：</p>
<pre><code class="language-js">const users = [
  {
    first_name: 'Mike',
    last_name: 'Sheridan'
  },
  {
    first_name: 'Tim',
    last_name: 'Lee'
  },
  {
    first_name: 'John',
    last_name: 'Carte'
  }
];

const usersList = users.map(function (user) {
  return `${user.first_name} ${user.last_name}`;
});

console.log(usersList); // ["Mike Sheridan", "Tim Lee", "John Carte"]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/abBJMqe?editors=0012">CodePen 演示</a>。</p>
<p>如果你想得到数组中特定的数据，数组的 <code>map</code> 方法也是有用的，如下：</p>
<pre><code class="language-js">const users = [
  {
    first_name: 'Mike',
    last_name: 'Sheridan',
    age: 30
  },
  {
    first_name: 'Tim',
    last_name: 'Lee',
    age: 45
  },
  {
    first_name: 'John',
    last_name: 'Carte',
    age: 25
  }
];

const surnames = users.map(function (user) {
  return user.last_name;
});

console.log(surnames); // ["Sheridan", "Lee", "Carte"]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/rNWyRdR?editors=0012">CodePen 演示</a>。</p>
<p>在上面的代码中，我们只把每个用户的姓提取出来，然后将它们存储在一个数组中。</p>
<p>我们还可以使用 <code>map</code> 生成一个动态内容如下：</p>
<pre><code class="language-js">const users = [
  {
    first_name: 'Mike',
    location: 'London'
  },
  {
    first_name: 'Tim',
    location: 'US'
  },
  {
    first_name: 'John',
    location: 'Australia'
  }
];

const usersList = users.map(function (user) {
  return `${user.first_name} lives in ${user.location}`;
});

console.log(usersList); // ["Mike lives in London", "Tim lives in US", "John lives in Australia"]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/ExNWMOY?editors=0012">CodePen 演示</a>。</p>
<p>注意在上面的代码中，我们并没有改变原始的 <code>users</code> 数组。我们创建了一个新的动态内容数组，因为 <code>map</code> 总是返回一个新的数组。</p>
<h3 id="map">使用 map 方法的优点</h3>
<ul>
<li>可以在不改变原数组的同时快速生成一个新数组</li>
<li>可以基于每个元素生成一个动态内容的数组</li>
<li>可以快速提取数组中的任意一个元素</li>
<li>它能生成一个与原数组长度相同的数组</li>
</ul>
<p><strong>浏览器支持</strong></p>
<ul>
<li>IE9 版本及以上和所有现代浏览器</li>
<li>Edge12 版本及以上</li>
</ul>
<h2 id="arrayfind">Array.find 方法</h2>
<p><code>Array.find</code> 方法的语法如下：</p>
<pre><code class="language-js">Array.find(callback(element[, index[, array]])[, thisArg])
</code></pre>
<blockquote>
<p><code>_find_</code> <em>方法返回数组中满足给定条件的</em> <code>_第一个元素_</code>的 <code>_值_</code>。</p>
</blockquote>
<p><code>find</code> 方法将 callback 函数作为第一个 argument 对象，并为数组中的每个元素执行 callback 函数。每个数组中的元素值都被作为第一个参数传到 <code>callback</code> 函数中。</p>
<p>设想我们有这样一个应聘者列表：</p>
<pre><code class="language-js">const employees = [
 { name: "David Carlson", age: 30 },
 { name: "John Cena", age: 34 },
 { name: "Mike Sheridan", age: 25 },
 { name: "John Carte", age: 50 }
];
</code></pre>
<p>我们想得到姓名是 <code>John</code> 的应聘者记录，在这种情况下，我们可以使用 <code>find</code> 方法，如下：</p>
<pre><code class="language-js">const employee = employees.find(function (employee) {
  return employee.name.indexOf('John') &gt; -1;
});

console.log(employee); // { name: "John Cena", age: 34 }
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/VwmpVmL?editors=0011">CodePen 演示</a>。</p>
<p>尽管列表中有 <code>"John Carte"</code> ，但 <code>find</code> 方法在第一次匹配后就会停止。因此它不会返回名为 <code>"John Carte"</code> 的这个对象。</p>
<p>与上例相同的 for 循环代码如下：</p>
<pre><code class="language-js">const employees = [
 { name: "David Carlson", age: 30 },
 { name: "John Cena", age: 34 },
 { name: "Mike Sheridan", age: 25 },
 { name: "John Carte", age: 50 }
];

let user;

for(let i = 0; i &lt; employees.length; i++) {
  if(employees[i].name.indexOf('John') &gt; -1) {
    user = employees[i];
    break;
  }
}

console.log(user); // { name: "John Cena", age: 34 }
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/BaQWbeY?editors=0012">CodePen 演示</a>。</p>
<p>可以看到的是，使用普通的 for 循环会使代码量更大并且更难理解。但是使用 <code>find</code> 方法，我们可以通过容易理解的方式写出同样的代码。</p>
<h3 id="find">find 方法的优点</h3>
<ul>
<li>我们可以不用写大量代码就快速找到任意一个元素</li>
<li>找到匹配元素后会立即停止循环，因此不用写额外的 break 语句</li>
</ul>
<p><strong>浏览器支持</strong></p>
<ul>
<li>除 IE 之外的所有现代浏览器</li>
<li>Edge 12 版本及以上</li>
</ul>
<h2 id="arrayfindindex">Array.findIndex 方法</h2>
<p><code>Array.findIndex</code> 方法的语法如下：</p>
<pre><code class="language-js">Array.findIndex(callback(element[, index[, array]])[, thisArg])
</code></pre>
<p><code>findIndex</code> 方法返回数组中 <strong>满足给定测试条件</strong> 的第一个元素的 <strong>索引</strong>。否则返回 <code>-1</code>，表示没有元素通过检测。</p>
<pre><code class="language-js">const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridan', age: 25 },
  { name: 'John Carte', age: 50 }
];

const index = employees.findIndex(function (employee) {
  return employee.name.indexOf('John') &gt; -1;
});

console.log(index); // 1
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/JjbWebQ?editors=0012">CodePen 演示</a>。</p>
<p>这里我们得到的输出 <strong>1</strong> 就是名为 <code>John</code> 的第一个对象的索引。注意索引是从0开始的。</p>
<p>与上面例子的效果相同的 for 循环代码如下：</p>
<pre><code class="language-js">const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridan', age: 25 },
  { name: 'John Carte', age: 50 }
];

let index = -1;

for(let i = 0; i &lt; employees.length; i++) {
  if(employees[i].name.indexOf('John') &gt; -1) {
    index = i;
    break;
  }
}

console.log(index); // 1
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/oNYZOgY?editors=0012">CodePen 演示</a>。</p>
<h3 id="findindex">使用 findIndex 的优点</h3>
<ul>
<li>能让我们不用写大量代码就快速找到元素的索引</li>
<li>找到匹配元素后会立即停止循环，因此不用写额外的 break 语句</li>
<li>我们也可以用 <code>find</code> 方法来找到索引，但是使用 <code>findIndex</code> 会更简单，且能避免额外创建变量来存储索引</li>
</ul>
<p><strong>浏览器支持</strong></p>
<ul>
<li>除 IE 之外的所有现代浏览器</li>
<li>Edge 12 版本及以上</li>
</ul>
<h2 id="arrayfilter">Array.filter 方法</h2>
<p><code>Array.filter</code> 方法的语法如下：</p>
<pre><code class="language-js">Array.filter(callback(element[, index[, array]])[, thisArg])
</code></pre>
<p><code>filter</code> 方法返回一个符合给定测试条件所有元素组成的 <code>新数组</code> 。</p>
<p><code>filter</code> 方法将 callback 函数作为第一个 argument 对象，并为数组中的每一个元素执行该 callback 函数。数组中的每个元素值被作为第一个参数传递到 callback 函数中。</p>
<pre><code class="language-js">const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridan', age: 25 },
  { name: 'John Carte', age: 50 }
];

const employee = employees.filter(function (employee) {
  return employee.name.indexOf('John') &gt; -1;
});

console.log(employee); // [ { name: "John Cena", age: 34 }, { name: "John Carte", age: 50 }]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/yLVMQgE?editors=0011">CodePen 演示</a>。</p>
<p>从上面的代码里可以看出，使用 <code>filter</code> 方法能找出数组中所有符合特定检测条件的元素。</p>
<p>因此使用 <code>filter</code> ，在找到数组中符合条件的元素时也不会停止搜索其他满足条件的元素，之后会返回所有满足条件的元素。</p>
<blockquote>
<p><code>find</code> 与 <code>filter</code> 的主要区别在于 <code>find</code> 只返回数组中匹配的第一个元素，而 <code>filter</code> 返回数组中所有匹配元素。</p>
</blockquote>
<p>注意 <code>filter</code> 方法返回的是一个数组，如果没有元素通过检测条件，将会返回一个空数组。</p>
<p>与上面例子的效果相同的 for 循环代码如下：</p>
<pre><code class="language-js">const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridan', age: 25 },
  { name: 'John Carte', age: 50 }
];

let filtered = [];

for(let i = 0; i &lt; employees.length; i++) {
 if(employees[i].name.indexOf('John') &gt; -1) {
   filtered.push(employees[i]);
 }
}

console.log(filtered); // [ { name: "John Cena", age: 34 }, { name: "John Carte", age: 50 }]
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/qBqrwaq?editors=0011">CodePen 演示</a>。</p>
<h3 id="filter">使用 filter 方法的优点</h3>
<ul>
<li>可以让我们快速找到数组中所有匹配的元素</li>
<li>不管有没有匹配到，都会返回一个数组，因此可以避免写额外的 <code>if</code> 条件</li>
<li>可以避免创建一个额外的变量来存储过滤后的元素</li>
</ul>
<p><strong>浏览器支持</strong></p>
<ul>
<li>IE9 及以上和所有现代浏览器</li>
<li>Edge 12 及以上</li>
</ul>
<h2 id="arrayevery">Array.every 方法</h2>
<p><code>Array.every</code> 方法的语法如下：</p>
<pre><code class="language-js">Array.every(callback(element[, index[, array]])[, thisArg])
</code></pre>
<p><code>every</code> 方法检测数组中的所有元素是否都通过给定的条件，并且返回一个布尔值 <code>true</code> 或者 <code>false</code> 。</p>
<p>假设有一个数字组成的数组，想检测是否数组中的每个元素都是正数，我们可以使用 <code>every</code> 方法来完成。</p>
<pre><code class="language-js">let numbers = [10, -30, 20, 50];

let allPositive = numbers.every(function (number) {
  return number &gt; 0;
});
console.log(allPositive); // false 

numbers = [10, 30, 20, 50];

allPositive = numbers.every(function (number) {
  return number &gt; 0;
});
console.log(allPositive); // true
</code></pre>
<p>假设有一个注册表格，你想在提交前检查是否所有必填项都已输入，就可以使用 <code>every</code> 方法来轻松检查表单的每一项。</p>
<pre><code class="language-js">window.onload = function () {
  const form = document.getElementById('registration_form');
  form.addEventListener('submit', function (event) {
    event.preventDefault();
    const fields = ['first_name', 'last_name', 'email', 'city'];
    const allFieldsEntered = fields.every(function (fieldId) {
      return document.getElementById(fieldId).value.trim() !== '';
    });

    if (allFieldsEntered) {
      console.log('All the fields are entered');
      // All the field values are entered, submit the form
    } else {
      alert('Please, fill out all the field values.');
    }
  });
};
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/rNWyQwo?editors=0011">CodePen 演示</a>。</p>
<p>上面 <code>every</code> 方法的回调函数中，我们检查表单的每一项是否都不为空，并且返回一个布尔值。</p>
<p>在上面的代码中，如果回调函数中，<code>fields</code> 数组中的每一项都返回 <code>true</code> ，那 <code>every</code> 方法就返回 <code>true</code> 。</p>
<p>如果 <code>fields</code> 数组中任意一个回调函数返回 <code>false</code> 值， <code>every</code> 方法就会返回 <code>false</code> 结果。</p>
<h3 id="every">使用 every 方法的优点</h3>
<ul>
<li>能让我们不用写大量代码就快速检测出是否所有元素都满足特定的标准</li>
</ul>
<h3 id="">浏览器支持</h3>
<ul>
<li>IE9 及以上和所有现代浏览器</li>
<li>Edge 12 及以上</li>
</ul>
<h2 id="arraysome">Array.some 方法</h2>
<p><code>Array.some</code> 方法的语法如下：</p>
<pre><code class="language-js"> Array.some(callback(element[, index[, array]])[, thisArg]
</code></pre>
<p><code>some</code> 方法检测数组中是否至少有一个元素通过给定函数的检测条件，并且返回一个 <code>true</code> 或 <code>false</code> 的布尔值。</p>
<p>一旦找到第一个匹配元素，会立即返回 <code>true</code> ，如果没有，则会返回 <code>false</code> 。</p>
<p>假定有一个数字组成的数组，我们想检测数组中是否至少包含一个正数，就可以使用 <code>some</code> 方法来完成。</p>
<pre><code class="language-js">let numbers = [-30, 40, 20, 50];

let containsPositive = numbers.some(function (number) {
  return number &gt; 0;
});
console.log(containsPositive); // true 

numbers = [-10, -30, -20, -50];

containsPositive = numbers.every(function (number) {
  return number &gt; 0;
});
console.log(containsPositive); // false
</code></pre>
<p>这里有一些使用 <code>some</code> 方法的有用场景：</p>
<h3 id="some1"><code>Some</code> 方法示例 1</h3>
<p>假设有一个应聘者的列表，我们想检查某个特定的应聘者是否在这个数组中，如果有的话，同时要得到在数组总的索引位置。</p>
<p>因此我们可以使用 <code>some</code> 方法同时得到这两个值，而不用分别单独使用 <code>find</code> 和 <code>findIndex</code> 方法。</p>
<pre><code class="language-js">const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridon', age: 25 },
  { name: 'John Carte', age: 50 }
];

let indexValue = -1;
const employee = employees.some(function (employee, index) {
  const isFound = employee.name.indexOf('John') &gt; -1;
  if (isFound) {
    indexValue = index;
  }
  return isFound;
});

console.log(employee, indexValue); // true 1
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/ExNWOvz?editors=0011">CodePen 演示</a>。</p>
<h3 id="some2"><code>Some</code> 方法示例 2</h3>
<p><code>forEach</code>、<code>map</code> 和 <code>filter</code> 方法会将数组中的所有元素从头到尾执行一次。没有终止循环的方法，除非找到特定的元素。</p>
<p>在这种情况下，我们可以使用数组的 <code>some</code> 方法。 <code>map</code>、<code>forEach</code> 和 <code>some</code> 方法的回调函数传递的参数都相同。</p>
<ul>
<li>第一个参数是当前值</li>
<li>第二个参数是当前索引</li>
<li>第三个参数是原始数组</li>
</ul>
<p>如上面例 1 中看到的，一旦找到特定的匹配值， <code>some</code> 方法就会停止循环。</p>
<h3 id="some">使用 some 方法的优点</h3>
<ul>
<li>能让我们不用写大量代码就快速检测是否有匹配一定标准的元素</li>
<li>能快速终止循环，这是上面其他循环方法没有的</li>
</ul>
<h3 id="">浏览器支持</h3>
<ul>
<li>IE9 及以上和所有现代浏览器</li>
<li>Edge 12 及以上</li>
</ul>
<h2 id="arrayreduce">Array.reduce 方法</h2>
<p><code>Array.reduce</code> 方法的语法如下：</p>
<pre><code class="language-js">Array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
</code></pre>
<p><code>reduce</code> 方法对数组中的每个元素执行一个由你提供的 <strong>reducer</strong> 函数，将其结果汇总为单个返回值。</p>
<blockquote>
<p>注意 <code>reduce</code> 方法的输出总是一个单一的值。它可以是一个对象、一个数字、一个字符串、一个数组等等，这取决于你想要 <code>reduce</code> 方法输出那种，但它总是一个单一的值。</p>
</blockquote>
<p>如果你想求数组中所有数字的和，可以用 <code>reduce</code> 方法。</p>
<pre><code class="language-js">const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce(function(accumulator, number) {
  return accumulator + number; 
}, 0);

console.log(sum); // 15
</code></pre>
<p>这里是<a href="https://codepen.io/myogeshchavan97/pen/ExNWzmo?editors=0012">CodePen 演示</a>。</p>
<p><code>reduce</code> 方法接收一个回调函数，参数为 <code>accumulator</code>, <code>number</code>, <code>index</code> 和 <code>array</code> 。在上面的代码中，我们只使用了 <code>accumulator</code> 和 <code>number</code>。</p>
<p><code>accumulator</code> 包含数组中要用到的 <code>initialValue</code> 。<code>initialValue</code> 决定了 <code>reduce</code> 方法返回的数据类型。</p>
<p><code>number</code> 是回调函数中的第二个参数，包含循环中的每个枚举值。</p>
<p>上面的代码中，我们提供了 <code>0</code> 作为 <code>accumulator</code> 的 <code>initialValue</code> 。因此回调函数第一次执行时，<code>accumulator + number</code> 是 <code>0 + 1 = 1</code> ，返回值是 <code>1</code>。</p>
<p>下一次回调函数运行时，<code>accumulator + number</code> 是 <code>1 + 2 = 3</code> （这里的 <code>1</code> 是上次迭代返回的值，<code>2</code> 是数组中下一个元素）。</p>
<p>下一次运行，<code>accumulator + number</code> 就是 <code>3 + 3 = 6</code>（这里的第一个 <code>3</code> 是上次迭代的返回值，下一个 <code>3</code> 是数组中下一个元素），并且这会持续到数组中的 <code>numbers</code> 不再迭代。</p>
<p>因此 <code>accumulator</code> 会保持上一次操作的值，就像一个静态变量。</p>
<p>上面的代码中，<code>initialValue</code> 的 <code>0</code> 并不是必须的，因为数组中的元素都是整数。</p>
<p>因此下面的代码同样可行：</p>
<pre><code class="language-js">const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce(function (accumulator, number) {
  return accumulator + number;
});

console.log(sum); // 15
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/ExNWObz?editors=0012">CodePen 演示</a>。</p>
<p>这里的 <code>accumulator</code> 包含数组中的第一个元素，<code>number</code> 包含数组中的下一个元素（第一次迭代是 <code>1 + 2 = 3</code> ，第二次迭代是 <code>3 + 3 = 6</code> ，以此类推）。</p>
<p>但搞清楚 <code>accumulator</code> 的 <code>initialValue</code> 也是很有用的，因为这能让你更容易理解 <code>reduce</code> 方法的返回类型，并且得到正确类型的返回值。</p>
<p>请看以下代码：</p>
<pre><code class="language-js">const numbers = [1, 2, 3, 4, 5];

const doublesSum = numbers.reduce(function (accumulator, number) {
  return accumulator + number * 2;
}, 10);

console.log(doublesSum); // 40
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/jOVBQYx?editors=0012">CodePen 演示</a>。</p>
<p>这里我们给数组中的每个元素乘以 2。我们给 <code>accumulator</code> 提供了一个 <code>initialValue</code> 为 10，因此 10 被加到总和结果中，如下：</p>
<pre><code class="language-js">[1 * 2, 2 * 2, 3 * 2, 4 * 2, 5 * 2] = [2, 4, 6, 8, 10] = 30 + 10 = 40
</code></pre>
<p>假设一个有 x 和 y 坐标的对象数组，你想得到 x 坐标的和，就可以使用 <code>reduce</code> 方法。</p>
<pre><code class="language-js">const coordinates = [
  { x: 1, y: 2 }, 
  { x: 2, y: 3 }, 
  { x: 3, y: 4 }
];

const sum = coordinates.reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x;
}, 0);

console.log(sum); // 6
</code></pre>
<p>这里是 <a href="https://codepen.io/myogeshchavan97/pen/OJbpaOg?editors=0012">CodePen 演示</a>。</p>
<h3 id="reduce">使用 reduce 方法的优点</h3>
<ul>
<li>使用 <code>reduce</code> 可以基于数组生成任何简单或者复杂类型的数据</li>
<li>它能记住循环中之前的返回值，因此可以避免创建一个保存历史值的全局变量</li>
</ul>
<h3 id="">浏览器支持</h3>
<ul>
<li>IE9 及以上和所有现代浏览器</li>
<li>Edge 12 及以上</li>
</ul>
<h3 id="">感谢阅读！</h3>
<p>想要详细学习更多包括 <code>let</code> 和 <code>const</code>、promise、数组与对象解构、数组方法、async/await、import/export 等其他 ES6+ 的特性？</p>
<p>点击查看我的书：<a href="https://yogeshchavan1.podia.com/mastering-modern-javascript?coupon=LA1HR55">《掌握现代 JavaScript》</a>。这本书为你学习 React 做准备，并且帮助你更好的掌握 JavaScript 和 React。</p>
<p>也可以通过我的免费课程 <a href="https://yogeshchavan1.podia.com/react-router-introduction">React Router 介绍</a> 来从头学习 React Router。</p>
<p><strong>想要紧跟最新 JavaScript、React、Node.js 的内容？<a href="https://www.linkedin.com/in/yogesh-chavan97/">在 LinkedIn 上关注我</a>。</strong></p>
<!--kg-card-end: markdown--> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 使用 JavaScript split() 方法将字符串分割为数组 ]]>
                </title>
                <description>
                    <![CDATA[ 原文：JavaScript split() a String – String to Array JS Method [https://www.freecodecamp.org/news/javascript-split-a-string-string-to-array-js-method/] ，作者：Jessica Wilkins [https://www.freecodecamp.org/news/author/jessica-wilkins/] 如果你需要将一个字符串分割成一个子字符串的数组，那么你可以使用JavaScript split() 方法。 在这篇文章中，我将介绍 JavaScript split() 方法并提供代码示例。 split() 方法的基本语法 下面是 JavaScript split() 方法的语法。 str.split(optional-separator, optional-limit) optional-separator 参数是一种模式，它告诉计算机应该在哪里分割。 optional-limit 参数是一个正数，告诉计算机在返回的数组值中 ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/javascript-split-a-string-string-to-array-js-method/</link>
                <guid isPermaLink="false">625e90f199ec7406219e6dbf</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chengjun.L ]]>
                </dc:creator>
                <pubDate>Tue, 19 Apr 2022 04:20:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/04/pankaj-patel-1IW4HQuauSU-unsplash.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>原文：<a href="https://www.freecodecamp.org/news/javascript-split-a-string-string-to-array-js-method/">JavaScript split() a String – String to Array JS Method</a>，作者：<a href="https://www.freecodecamp.org/news/author/jessica-wilkins/">Jessica Wilkins</a></p><p>如果你需要将一个字符串分割成一个子字符串的数组，那么你可以使用JavaScript <code>split()</code> 方法。</p><p>在这篇文章中，我将介绍 JavaScript <code>split()</code> 方法并提供代码示例。</p><h2 id="split-">split() 方法的基本语法</h2><p>下面是 JavaScript <code>split()</code> 方法的语法。</p><pre><code class="language-js">str.split(optional-separator, optional-limit)</code></pre><p><code>optional-separator</code> 参数是一种模式，它告诉计算机应该在哪里分割。</p><p><code>optional-limit</code> 参数是一个正数，告诉计算机在返回的数组值中应该有多少个子字符串。</p><h2 id="javascript-split-">JavaScript split() 方法代码示例</h2><p>在这第一个例子中，我有一个字符串 <code>"I love freeCodeCamp"</code>。如果我使用没有分隔符的 <code>split()</code> 方法，那么返回值将是整个字符串的数组。</p><pre><code class="language-js">const str = 'I love freeCodeCamp';

str.split();
// 返回值是 ["I love freeCodeCamp"]</code></pre><h3 id="-">使用分隔符参数的例子</h3><p>如果我想改变它，使字符串被分割成单个字符，那么我需要添加一个分隔符。分隔符将是一个空字符串。</p><pre><code class="language-js">const str = 'I love freeCodeCamp';

str.split('');
// 返回值 ["I", " ", "l", "o", "v", "e", " ", "f", "r", "e", "e", "C", "o", "d", "e", "C", "a", "m", "p"]</code></pre><p>请注意，在返回值中，空格被视为字符。</p><p>如果我想改变它，使字符串被分割成各个单词，那么分隔符将是一个带有空格的空字符串。</p><pre><code class="language-js">const str = 'I love freeCodeCamp';

str.split(' ');
// 返回值 ["I", "love", "freeCodeCamp"]</code></pre><h3 id="-limit-">使用 limit 参数的例子</h3><p>在这个例子中，我将使用 limit 参数来返回一个只包含句子 <code>"I love freeCodeCamp"</code> 的第一个单词的数组。</p><pre><code class="language-js">const str = 'I love freeCodeCamp';

str.split(' ',1);
// 返回值 ["I"]</code></pre><p>如果我把 limit 改为零，那么返回值将是一个空数组。</p><pre><code class="language-js">const str = 'I love freeCodeCamp';

str.split(' ',0);
//返回值 []</code></pre><h2 id="-split-">你应该使用 split() 方法来反转一个字符串吗</h2><p>反转字符串的练习是一个非常流行的编码挑战。解决它的一个常见方法是使用 <code>split()</code> 方法。</p><p>在这个例子中，我们有一个字符串 “freeCodeCamp”。如果我们想反转这个词，那么我们可以把 <code>split()</code>、<code>reverse()</code> 和 <code>join()</code> 方法连在一起，以返回新的反转字符串。</p><pre><code class="language-js">const str = 'freeCodeCamp';

str.split('').reverse().join('');
//返回值 "pmaCedoCeerf"</code></pre><p><code>.split('')</code> 部分将字符串分割成一个字符数组。</p><p><code>.reverse()</code> 部分将字符数组反转。</p><p><code>.join('')</code> 部分将数组中的字符连接起来并返回一个新的字符串。</p><p>这种方法似乎对这个例子很有效。但在一些特殊情况下，这种方法是行不通的。</p><p>让我们看一下 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split">MDN 文档</a>中提供的例子。</p><p>如果我们试图反转字符串 “mañana mañana”，那么就会导致意外的结果。</p><pre><code class="language-js">const str = 'mañana mañana'
const reversedStr = str.split('').reverse().join('')

console.log(reversedStr)
// 返回值将是 "anãnam anañam"</code></pre><p>Notice how the tilde(~) is placed over the letter <code>"a"</code> instead of <code>"n"</code> in the reversed word. This happens because our string contains what is called a grapheme.</p><p>A grapheme cluster is a series of symbols combined to produce one single character that humans can read on screen. When we try to reverse the string using these types of characters, the computer can misinterpret these characters and produce an incorrect version of the reversed string.</p><p>If we just isolate the split method, you can see how the computer is breaking up each individual character.</p><p>注意到在反转的单词中，波浪线（~）是如何放在字母 <code>"a"</code> 而不是 <code>"n"</code> 上面的。发生这种情况是因为我们的字符串包含了所谓的字素。</p><p>字素簇是一系列符号组合成的一个单一字符，人类可以在屏幕上阅读。当我们试图用这些类型的字符来反转字符串时，计算机会误解这些字符，并产生一个不正确的反转字符串版本。</p><p>如果我们只是孤立的分割方法，你可以看到计算机是如何分割每个单独的字符的。</p><pre><code class="language-js">const str = 'mañana mañana'

console.log(str.split(''))
//["m", "a", "ñ", "a", "n", "a", " ", "m", "a", "n", "̃", "a", "n", "a"]</code></pre><p>如果你使用这些特殊字符，你可以在你的项目中使用一些<a href="https://github.com/mathiasbynens/esrever">包</a>来修复这个问题，并正确地反转字符串。</p><h2 id="--1">总结</h2><p>JavaScript <code>split()</code> 方法是用来将一个字符串分割成一个子字符串数组的。</p><p>下面是 JavaScript <code>split()</code> 方法的语法。</p><pre><code class="language-js">str.split(optional-separator, optional-limit)</code></pre><p>分隔符是一种模式，它告诉计算机每个分割应该发生在哪里。</p><p>limit 参数是一个正数，告诉计算机在返回的数组值中应该有多少个子字符串。</p><p>你可以使用 <code>split()</code> 方法来反转一个字符串，但是在一些特殊情况下这是行不通的。如果你的字符串中包含字素簇，那么结果可能会产生一个不正确的反转词。</p><p>你也可以选择使用 <code>spread()</code> 语法，在反转字符串之前将其拆分。</p><pre><code class="language-js">const str = 'mañana mañana'
console.log([...str].reverse().join(""))</code></pre><p>我希望你喜欢这篇文章，并祝你在 JavaScript 之旅中好运。</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Java 数组——如何在 Java 中声明和初始化一个数组 ]]>
                </title>
                <description>
                    <![CDATA[ 原文：Java Array – How to Declare and Initialize an Array in Java Example [https://www.freecodecamp.org/news/java-array-how-to-declare-and-initialize-an-array-in-java-example/] ，作者：Ihechikara Vincent Abba [https://www.freecodecamp.org/news/author/ihechikara/] 在这篇文章中，我们将讨论 Java 中的数组。我将通过一些例子来帮助你理解什么是数组，如何声明数组，以及如何在你的 Java 代码中使用它们。 什么是数组 在 Java 中，你用数组来在一个变量中存储多个相同数据类型的值。你也可以把它看作是同一数据类型的值的集合。这意味着如果你要在数组中存储字符串，那么你的数组中的所有值都应该是字符串。 如何在 Java 中声明一个数组 我们使用方括号 [] 来声明一个数组： String[] names; 我们已经声明了一个名为 nam ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/java-array-how-to-declare-and-initialize-an-array-in-java-example/</link>
                <guid isPermaLink="false">621df0e879a578061070cf21</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chengjun.L ]]>
                </dc:creator>
                <pubDate>Mon, 07 Mar 2022 08:00:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/03/andrew-moca-yAGNjU4rtss-unsplash-1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>原文：<a href="https://www.freecodecamp.org/news/java-array-how-to-declare-and-initialize-an-array-in-java-example/">Java Array – How to Declare and Initialize an Array in Java Example</a>，作者：<a href="https://www.freecodecamp.org/news/author/ihechikara/">Ihechikara Vincent Abba</a></p><p>在这篇文章中，我们将讨论 Java 中的数组。我将通过一些例子来帮助你理解什么是数组，如何声明数组，以及如何在你的 Java 代码中使用它们。</p><h2 id="-">什么是数组</h2><p>在 Java 中，你用数组来在一个变量中存储多个相同数据类型的值。你也可以把它看作是同一数据类型的值的集合。这意味着如果你要在数组中存储字符串，那么你的数组中的所有值都应该是字符串。</p><h2 id="-java-">如何在 Java 中声明一个数组</h2><p>我们使用方括号 <code>[]</code> 来声明一个数组：</p><pre><code class="language-java">String[] names;</code></pre><p>我们已经声明了一个名为 <code>names</code> 的变量，它将保存一个字符串数组。</p><p>如果我们要为整数声明一个变量，那么我们会这样做：</p><pre><code class="language-java">int[] myIntegers;</code></pre><p>所以要创建一个数组，你要指定将存储在数组中的数据类型，后面加方括号，然后是数组的名称。</p><h2 id="-java--1">如何在 Java 中初始化一个数组</h2><p>初始化一个数组只是意味着给数组赋值。让我们来初始化我们在上一节中声明的数组。</p><pre><code class="language-java">String[] names = {"John", "Jade", "Love", "Allen"};</code></pre><pre><code class="language-java">int[] myIntegers = {10, 11, 12};</code></pre><p>我们通过传入相同数据类型的值来初始化数组，每个值用逗号隔开。</p><p>如果我们想访问数组中的元素/值，我们将参考它们在数组中的索引号。第一个元素的索引是 0。下面是一个例子：</p><pre><code class="language-java">String[] names = {"John", "Jade", "Love", "Allen"};

System.out.println(names[0]);
// John

System.out.println(names[1]);
// Jade

System.out.println(names[2]);
// Love

System.out.println(names[3]);
// Allen</code></pre><p>现在我们知道了如何访问每个元素，让我们来改变第三个元素的值：</p><pre><code class="language-java">String[] names = {"John", "Jade", "Love", "Allen"};
names[2] = "Victor";

System.out.println(names[2]);
// Victor</code></pre><p>我们还可以使用 <code>length</code> 属性检查数组的长度，例如：</p><pre><code class="language-java">String[] names = {"John", "Jade", "Love", "Allen"};
System.out.println(names.length);
// 4</code></pre><h2 id="-java--2">如何在 Java 中遍历一个数组</h2><p>我们可以使用 <code>for</code> 循环来遍历一个数组中的元素。</p><pre><code class="language-java">String[] names = {"John", "Jade", "Love", "Allen"};
for (int i = 0; i &lt; names.length; i++) {
  System.out.println(names[i]);
}

// John
// Jade
// Love
// Allen</code></pre><p>上面的循环将打印我们数组中的元素。我们使用了 <code>length</code> 属性来指定循环运行的次数。</p><h2 id="--1">小结</h2><p>在这篇文章中，我们学习了如何在 Java 代码中声明和初始化数组。我们还看到了如何访问数组中的每个元素，以及如何在这些元素中循环。</p><p>祝你编程愉快！</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Java 数组声明和在 Java 中初始化数组（含代码示例） ]]>
                </title>
                <description>
                    <![CDATA[ 数组是 Java 基本数据结构的重要组成部分，它们在解决许多编程问题方面非常有用。 什么是数组 根据定义，数组是相同类型数据的集合。 声明一个数组，你就可以在同一个内存中拥有多个值——不像变量，你只能在内存中拥有一个值。 因此，数组让你可以创建一个将不同的值保存在一起的变量，而不是为每个值声明一个变量。 数组中特定数据点的位置被称为其索引，而数据本身被称为元素。 在本教程中，我将向你展示如何声明一个数组，初始化它，并使用 for 循环和增强的 for 循环遍历它。 然后你可以开始在你的 Java 项目中使用它。 我将使用 intelliJIDEA IDE 来编写代码。你可以根据需要使用它，也可以使用你选择的任何 IDE。 如何在 Java 中声明和初始化数组 在 Java 中有两种方法可以声明和初始化数组。第一个是使用 new 关键字，你必须在其中一个一个地初始化值。第二种方法是将值放在花括号中。 如何使用 new 关键字初始化数组 你可以使用以下语法声明数组： dataType [ ] nameOfArray; dataType：要放入数组的数据类型。这可以是字 ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/java-array-declaration-how-to-initialize-an-array-in-java-with-example-code/</link>
                <guid isPermaLink="false">613ecaa0b201730648bd9c3d</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Miya Liu ]]>
                </dc:creator>
                <pubDate>Fri, 10 Sep 2021 03:00:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2021/09/javaArrays.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>数组是 Java 基本数据结构的重要组成部分，它们在解决许多编程问题方面非常有用。</p><h2 id="-">什么是数组</h2><p>根据定义，数组是相同类型数据的集合。</p><p>声明一个数组，你就可以在同一个内存中拥有多个值——不像变量，你只能在内存中拥有一个值。</p><p>因此，数组让你可以创建一个将不同的值保存在一起的变量，而不是为每个值声明一个变量。</p><p>数组中特定数据点的位置被称为其索引，而数据本身被称为元素。</p><p>在本教程中，我将向你展示如何声明一个数组，初始化它，并使用 for 循环和增强的 for 循环遍历它。 然后你可以开始在你的 Java 项目中使用它。</p><p>我将使用 intelliJIDEA IDE 来编写代码。你可以根据需要使用它，也可以使用你选择的任何 IDE。</p><h2 id="-java-">如何在 Java 中声明和初始化数组</h2><p>在 Java 中有两种方法可以声明和初始化数组。第一个是使用 <code>new</code> 关键字，你必须在其中一个一个地初始化值。第二种方法是将值放在花括号中。</p><h3 id="-new-">如何使用 <code>new</code> 关键字初始化数组</h3><p>你可以使用以下语法声明数组：</p><pre><code class="language-java">dataType [ ] nameOfArray;
</code></pre><p><code>dataType</code>：要放入数组的数据类型。这可以是字符串、整数、双精度值等。</p><p><code>[ ]</code>：表示要声明的变量将包含数组。</p><p><code>nameOfArrary</code>：数组标识符。</p><p>有了上面的信息，你只声明了数组——你还需要初始化它。</p><p>以这种方式初始化数组的基本语法如下所示：</p><pre><code class="language-java">dataType [] nameOfArray = new dataType [size]
</code></pre><p>大小通常用数值表示，它表示你想在数组中保存多少个值。它的值是不可变的，这意味着你将无法放入超过指定为数组大小的数字。</p><p>你现在可以将值放入数组中，如下所示：</p><pre><code class="language-java">package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // 在这里写你的代码
String [] names = new String[3];
names[0] = "Quincy";
names[1] = "Abbey";
names[2] = "Kolade";
   }
}
</code></pre><p>在上面的代码片段中，我初始化了一个名为 names（标识符）的字符串数组，大小是 3，所以它只能容纳三个值。</p><p>总共有3个索引：</p><ul><li>第一个值 <code>Quincy</code> 的索引是 <code>0</code></li><li>第二个值 <code>Abbey</code> 的索引是 <code>1</code></li><li>第三个值 <code>Kolade</code> 的索引是 <code>2</code></li></ul><p>不要被数字 0、1、2 弄得迷糊。数组是从 0 开始计数，而不是从 1 开始。</p><p>在上面的数组中，如果你添加额外的数据——例如，<code>names[3] = “Chris”</code>——你会得到一个错误，因为你已经指定了数组应该只包含 3 个值。如果要添加更多值，则必须增加数组的大小。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2021/09/error-1.png" class="kg-image" alt="error-1" width="600" height="400" loading="lazy"></figure><p>要将数组打印到控制台，你可以使用内置的 <code>toString()</code> 方法：</p><pre><code class="language-java">System.out.println(Arrays.toString(names));
</code></pre><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2021/09/names-print.png" class="kg-image" alt="names-print" width="600" height="400" loading="lazy"></figure><h3 id="2-"><strong>2. 如何在一行中初始化数组</strong></h3><p>你可以使用如下基本的语法在一行代码中初始化一个数组：</p><pre><code class="language-java">dataType [ ] nameOfArray = {value1, value2, value3, value4}

</code></pre><p>使用此方法，你无需指定数组的大小，因此你可以在其中放入任意数量的值。</p><p>查看下面代码片段中的示例：</p><pre><code class="language-java">package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // write your code here
     String [] namesTwo = {"Quincy", "Abbey", "Kolade", "Chris", "Kayode"};
  }
}
</code></pre><p>将数组打印到控制台显示如下值：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2021/09/names-print-2.png" class="kg-image" alt="names-print-2" width="600" height="400" loading="lazy"></figure><h2 id="-java--1">如何在 Java 中循环遍历数组</h2><p>你可以使用 <code>for</code> 循环和增强的 <code>for</code> 循环遍历 Java 中的数组。使用 <code>for</code> 循环，你可以访问各个值的索引，但使用增强的 <code>for</code> 循环，你不能这么做。</p><h3 id="-for-">如何使用 <code>for</code> 循环遍历数组</h3><p>在 Java 中，你可以使用 <code>for</code> 循环的基本语法：</p><pre><code class="language-java">for (dataType i = 0; i &lt; nameOfArray.length; i++) {
    //   要执行的代码
}
</code></pre><p>你可以像这样遍历 <code>namesTwo</code> 数组：</p><pre><code class="language-java">package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // 在这里写你的代码

        String [] namesTwo = {"Quincy", "Abbey", "Kolade", "Chris", "Kayode"};

        for (int i = 0; i &lt; namesTwo.length; i++) {
            System.out.println("Element at index " + i + " : " + namesTwo[i]);
        }
    }
}
</code></pre><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2021/09/for-loop.png" class="kg-image" alt="for-loop" width="600" height="400" loading="lazy"></figure><h3 id="-for--1">如何使用增强的 for 循环遍历数组</h3><p>增强的 <code>for</code> 循环是 <code>for</code> 循环的更清晰版本。缺点你无法使用它访问数组中各个值的索引。</p><p>增强的 <code>for</code> 循环的基本语法如下所示：</p><pre><code class="language-java">for (dataType variable : nameOfArray) {
    // 要执行的代码
}
</code></pre><pre><code class="language-java">package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // 在这里写你的代码

        String [] namesTwo = {"Quincy", "Abbey", "Kolade", "Chris", "Kayode"};

        for (String names : namesTwo) {
            System.out.println(names);
        }
    }
}
</code></pre><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2021/09/enhanced-for-loop.png" class="kg-image" alt="enhanced-for-loop" width="600" height="400" loading="lazy"></figure><h2 id="--1"><strong>总结</strong></h2><p>在本教程中，你学习了如何以两种不同的方式声明和初始化数组——使用 <code>new</code> 关键字和使用大括号。</p><p>你还学习了如何使用 <code>for</code> 循环和增强的 <code>for</code> 循环遍历数组，因此你不只是初始化数组，而什么都不做。</p><p>感谢你阅读本文！</p><p>原文：<a href="https://www.freecodecamp.org/news/java-array-declaration-how-to-initialize-an-array-in-java-with-example-code/">Java Array Declaration – How to Initialize an Array in Java with Example Code</a>，作者：<a href="https://www.freecodecamp.org/news/author/kolade/">Kolade Chris</a></p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Java 数组的打印方式 ]]>
                </title>
                <description>
                    <![CDATA[ 引言 数组是一种用来保存相同数据类型的数据结构。 数组的元素在内存中是连续存储的。 Java 中数组即对象。类的所有方法都被放进数组中调用。我们可以声明一个指定长度的数组。 声明一个基本数据类型数组： int[] intArray = {2,5,46,12,34}; 现在尝试使用System.out.println() 方法打印数组： System.out.println(intArray); // output: [I@74a14482 为什么 Java 没有打印出来数组数据呢？背后发生了什么事情？ 方法System.out.println() 通过调用String.valueOf() 把入参对象转换为一个字符串。 如果我们查看 String.valueOf() 方法的实现，会看到如下的代码： public static String valueOf(Object obj) {     return (obj == null) ? "null" : obj.toString(); } 如果入参是null 会返回空， 其它情况会调用obj.toString()。 ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/java-array-methods-how-to-print-an-array-in-java/</link>
                <guid isPermaLink="false">5fb132d35f583f05650910da</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 后端开发 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ tengfei ]]>
                </dc:creator>
                <pubDate>Wed, 16 Jun 2021 09:06:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2021/04/photo-1565609823909-a46a1d79c401-1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="-">引言</h2><p>数组是一种用来保存相同数据类型的数据结构。 数组的元素在内存中是连续存储的。</p><p>Java 中数组即对象。类的所有方法都被放进数组中调用。我们可以声明一个指定长度的数组。</p><p>声明一个基本数据类型数组：</p><pre><code class="language-java">int[] intArray = {2,5,46,12,34};
</code></pre><p>现在尝试使用 &nbsp;<code>System.out.println()</code> &nbsp;方法打印数组：</p><pre><code class="language-java">System.out.println(intArray);
// output: [I@74a14482
</code></pre><p>为什么 Java 没有打印出来数组数据呢？背后发生了什么事情？</p><p>方法 &nbsp;<code>System.out.println()</code> &nbsp;通过调用 &nbsp;<code>String.valueOf()</code> &nbsp;把入参对象转换为一个字符串。 如果我们查看 &nbsp;<code>String.valueOf()</code> &nbsp;方法的实现，会看到如下的代码：</p><pre><code class="language-java">public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
</code></pre><p>如果入参是 &nbsp;<code>null</code> &nbsp;会返回空， 其它情况会调用 &nbsp;<code>obj.toString()</code>。 最后 &nbsp;<code>System.out.println()</code> &nbsp;调用 &nbsp;<code>toString()</code> &nbsp;方法打印出了字符串。</p><p>如果对象的类没有重写 &nbsp;<code>Object.toString()</code> &nbsp;方法并实现，那就会调用超类 &nbsp;<code>Object</code> &nbsp;的 &nbsp;<code>Object.toString()</code> &nbsp;方法。</p><p><code>Object.toString()</code> &nbsp;返回的是 &nbsp;<code>getClass().getName()+****‘@’****+Integer.toHexString(hashCode())</code>。 简化格式为：“class name @ object’s hash code”。</p><p>上文中输出的内容是 &nbsp;<code>[I@74a14482</code>， &nbsp;<code>[</code> &nbsp;表示数组， &nbsp;<code>I</code> &nbsp;表示 int 数据类型（数组的数据类型）。 &nbsp;<code>74a14482</code> &nbsp;是数组的无符号十六进制 hash 值。</p><p>当创建自定义类时，重写 &nbsp;<code>Object.toString()</code> &nbsp;方法是最佳的实践。</p><p>Java 中我们不能简单的使用 &nbsp;<code>System.out.println()</code> &nbsp;方法打印数组。 相反，下面的几种方法可以打印：</p><ol><li>循环：for 循环和 for-each 循环</li><li><code>Arrays.toString()</code> &nbsp;方法</li><li><code>Arrays.deepToString()</code> &nbsp;方法</li><li><code>Arrays.asList()</code> &nbsp;方法</li><li>Java Iterator interface</li><li>Java Stream API</li></ol><p>让我们来学习如何使用它们吧。</p><h2 id="1-for-for-each-">1. 循环：for 循环和 for-each 循环</h2><p>for 循环示例：</p><pre><code class="language-java">int[] intArray = {2,5,46,12,34};

for(int i=0; i&lt;intArray.length; i++){
    System.out.print(intArray[i]);
    // output: 25461234
}
</code></pre><p>Java 的包装类都重写了 &nbsp;<code>Object.toString()</code> &nbsp;，返回数组元素的字符串形式。</p><p>for-each 循环示例：</p><pre><code class="language-java">int[] intArray = {2,5,46,12,34};
for(int i: intArray){
    System.out.print(i);
    // output: 25461234
}
</code></pre><h2 id="2-arrays-tostring-">2. Arrays.toString() 方法</h2><p><code>Arrays.toString()</code> &nbsp;是 &nbsp;<code>java.util</code> &nbsp;包下数组类的一个静态方法。它返回指定数组内容的字符串形式。这种方法可以用来打印一维数组。</p><p>数组元素被转换为字符串，调用了 &nbsp;<code>String.valueOf()</code> &nbsp;方法，例如：</p><pre><code class="language-java">int[] intArray = {2,5,46,12,34};
System.out.println(Arrays.toString(intArray));
// output: [2, 5, 46, 12, 34]
</code></pre><p>对于引用类型的数组，确保重写该引用类的 &nbsp;<code>Object.toString()</code> &nbsp;方法。</p><p>例如：</p><pre><code class="language-java">public class Test {
    public static void main(String[] args) {
        Student[] students = {new Student("John"), new Student("Doe")};
    System.out.println(Arrays.toString(students));
    // output: [Student{name='John'}, Student{name='Doe'}]
}}
class Student {
    private String name;
public Student(String name){
    this.name = name;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
@Override
public String toString() {
    return "Student{" + "name='" + name + ''' + '}';
}
</code></pre><p>此方法不适用于多维数组。在多维数组中， &nbsp;<code>Object.toString()</code> &nbsp;会打印数组元素的内存地址而不是内容。</p><p>例如：</p><pre><code class="language-java">// creating multidimensional array
int[][] multiDimensionalArr = { {2,3}, {5,9} };
System.out.println(Arrays.toString(multiDimensionalArr));
// output: [[I@74a14482, [I@1540e19d]
</code></pre><p>借助 &nbsp;<code>Arrays.deepToString()</code> &nbsp;方法可以打印多维数组。</p><h2 id="3-arrays-deeptostring-">3. Arrays.deepToString() 方法</h2><p><code>Arrays.deepToString()</code> &nbsp;返回数组“深层内容”的字符串形式。</p><p>对于基本类型数组，通过重载调用 &nbsp;<code>Arrays.toString()</code> &nbsp;方法将其转换为字符串。</p><p>基本类型多维数组示例：</p><pre><code class="language-java">// creating multidimensional array
int[][] multiDimensionalArr = { {2,3}, {5,9} };
System.out.println(Arrays.deepToString(multiDimensionalArr));
// output: [[2, 3], [5, 9]]
</code></pre><p>对于引用类型数组，通过递归调用 &nbsp;<code>Arrays.deepToString()</code> &nbsp;方法将其转换为字符串。</p><pre><code class="language-java">Teacher[][] teachers = 
{{ new Teacher("John"), new Teacher("David") }, {new Teacher("Mary")} };
System.out.println(Arrays.deepToString(teachers));
// output: 
[[Teacher{name='John'}, Teacher{name='David'}],[Teacher{name='Mary'}]]
</code></pre><p>我们在 Teacher 类中重写了 &nbsp;<code>Object.toString()</code> &nbsp;方法。</p><p>如果你对递归调用感兴趣，请查看 &nbsp;<code>Arrays.deepToString()</code> &nbsp;方法的<a href="http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/be44bff34df4/src/share/classes/java/util/Arrays.java#l4611">源码</a>。</p><p><strong>NOTE:</strong> &nbsp;引用类型的一维数组也可以用 &nbsp;<code>Arrays.deepToString()</code> &nbsp;方法打印。 例如:</p><pre><code class="language-java">Integer[] oneDimensionalArr = {1,4,7};
System.out.println(Arrays.deepToString(oneDimensionalArr));
// output: [1, 4, 7]
</code></pre><h2 id="4-arrays-aslist-">4. Arrays.asList() 方法</h2><p>此方法返回固定大小（数组长度）的列表。</p><pre><code class="language-java">Integer[] intArray = {2,5,46,12,34};
System.out.println(Arrays.asList(intArray));
// output: [2, 5, 46, 12, 34]
</code></pre><p>因为 List 是对象列表集合，所以数据类型由 int 变为 Integer。当我们把数组转换为列表时，数组应该是引用类型。</p><p>Java 调用 &nbsp;<code>Arrays.**asList**(intArray).toString()</code> &nbsp;。其内部实现是列表元素调用了 &nbsp;<code>toString()</code> &nbsp;方法。</p><p>自定义 Teacher 类示例：</p><pre><code class="language-java">Teacher[] teacher = { new Teacher("John"), new Teacher("Mary") };
System.out.println(Arrays.asList(teacher));
// output: [Teacher{name='John'}, Teacher{name='Mary'}]
</code></pre><p><strong>NOTE:</strong> &nbsp;不能使用此方法打印多维数据。 例如：</p><pre><code class="language-java">Teacher[][] teachers = 
{{ new Teacher("John"), new Teacher("David") }, { new Teacher("Mary") }};
System.out.println(Arrays.asList(teachers));
// output: [[Lcom.thano.article.printarray.Teacher;@1540e19d, [Lcom.thano.article.printarray.Teacher;@677327b6] 
</code></pre><h2 id="5-java-iterator-interface">5. Java Iterator interface</h2><p>Iterator 接口和 for-each 循环类似，可以使用 Iterator 接口遍历数组元素并打印。</p><p>Collection 调用 &nbsp;<code>iterator()</code> &nbsp;方法创建 Iterator 对象。Iterator 对象可以遍历该集合的元素。</p><p>Iterator 接口打印数组示例：</p><pre><code class="language-java">Integer[] intArray = {2,5,46,12,34};
// creating a List of Integer
List&lt;Integer&gt; list = Arrays.asList(intArray);
// creating an iterator of Integer List
Iterator&lt;Integer&gt; it = list.iterator();
// if List has elements to be iterated
while(it.hasNext()) {
    System.out.print(it.next());
    // output: 25461234
}
</code></pre><h2 id="6-java-stream-api">6. Java Stream API</h2><p>Stream API 用于处理对象集合。 流是一个对象序列。流不能改变原始数据结构，它仅根据请求的操作提供结果。</p><p>借助终端操作 &nbsp;<code>forEach()</code> &nbsp;可以遍历流的每个元素。</p><p>例如：</p><pre><code class="language-java">Integer[] intArray = {2,5,46,12,34};
Arrays.stream(intArray).forEach(System.out::print);
// output: 25461234
</code></pre><p>现在我们掌握了 Java 数组的打印方式。</p><p>感谢阅读！</p><p>我的另一篇文章在 &nbsp;<a href="https://medium.com/@mvthanoshan9/object-oriented-programming-principles-in-java-820919dced1a">Medium</a>。</p><p><strong><strong>Happy Coding!</strong></strong></p><p>原文：<a href="https://www.freecodecamp.org/news/java-array-methods-how-to-print-an-array-in-java/">Java Array Methods – How to Print an Array in Java</a>，作者：Thanoshan MV</p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript 对象数组——如何使用 JS 数组方法创建、更新和循环对象 ]]>
                </title>
                <description>
                    <![CDATA[ 我平均每周处理 JSON 数据 18 次，而且我几乎每次都需要在 Google 搜索处理数据的方法。能不能有一份总是可以提供答案的完全指南呢？ 在本文中，我将分享在 JavaScript 中使用对象数组的基础知识。 如果你曾经使用过 JSON 结构，那么你就已经使用过 JavaScript 对象。JSON 的意思是 JavaScript Object Notation（JavaScript 对象表示法）。 创建对象是如此简单： {   "color": "purple",   "type": "minivan",   "registration": new Date('2012-02-03'),   "capacity": 7 } 这个对象代表一辆汽车。汽车可以有多种类型和颜色，每个对象代表一辆特定的汽车。 大多数时候你都是从外部服务获取此类数据。但是，有时你需要手动创建对象及其数组，就像我创建这个电子商店时所做的一样： 每个类别列表项在 HTML 中看起来是像这样： 我不想将此代码重复 12 次，这将使其无法维护。 创建一个对象数组 我们回到汽车。看一下这一组汽车 ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/javascript-array-of-objects-tutorial-how-to-create-update-and-loop-through-objects-using-js-array-methods/</link>
                <guid isPermaLink="false">605d5d934c5a5f0564330398</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chengjun.L ]]>
                </dc:creator>
                <pubDate>Fri, 26 Mar 2021 09:00:03 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2021/03/js-tutorial-cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>我平均每周处理 JSON 数据 18 次，而且我几乎每次都需要在 Google 搜索处理数据的方法。能不能有一份总是可以提供答案的完全指南呢？</p><p>在本文中，我将分享在 JavaScript 中使用对象数组的基础知识。</p><p>如果你曾经使用过 JSON 结构，那么你就已经使用过 JavaScript 对象。JSON 的意思是 JavaScript Object Notation（JavaScript 对象表示法）。</p><p>创建对象是如此简单：</p><pre><code class="language-js">{
  "color": "purple",
  "type": "minivan",
  "registration": new Date('2012-02-03'),
  "capacity": 7
}
</code></pre><p>这个对象代表一辆汽车。汽车可以有多种类型和颜色，每个对象代表一辆特定的汽车。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/purple.png" class="kg-image" alt="purple" width="600" height="400" loading="lazy"></figure><p>大多数时候你都是从外部服务获取此类数据。但是，有时你需要手动创建对象及其数组，就像我创建这个电子商店时所做的一样：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/categories.jpg" class="kg-image" alt="categories" width="600" height="400" loading="lazy"></figure><p>每个类别列表项在 HTML 中看起来是像这样：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/code.jpg" class="kg-image" alt="code" width="600" height="400" loading="lazy"></figure><p>我不想将此代码重复 12 次，这将使其无法维护。</p><h2 id="-"><strong>创建一个对象数组</strong></h2><p>我们回到汽车。看一下这一组汽车：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars.jpg" class="kg-image" alt="cars" width="600" height="400" loading="lazy"></figure><p>我们可以将它们写成这样的数组：</p><pre><code class="language-js">let cars = [
  {
    "color": "purple",
    "type": "minivan",
    "registration": new Date('2017-01-03'),
    "capacity": 7
  },
  {
    "color": "red",
    "type": "station wagon",
    "registration": new Date('2018-03-03'),
    "capacity": 5
  },
  {
    ...
  },
  ...
]
</code></pre><p>对象数组并非始终保持不变。我们几乎总是需要操作它们。因此，让我们看一下如何将对象添加到已经存在的数组中。</p><h3 id="-array-unshift-"><strong>使用 Array.unshift 在开头添加一个新对象</strong></h3><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/beginning.jpg" class="kg-image" alt="beginning" width="600" height="400" loading="lazy"></figure><p>我们可以使用 <code>Array.unshift</code> 在数组的开头添加一个新的对象。</p><pre><code class="language-js">let car = {
  "color": "red",
  "type": "cabrio",
  "registration": new Date('2016-05-02'),
  "capacity": 2
}
cars.unshift(car);
</code></pre><h3 id="-array-push-"><strong>使用 Array.push 在结尾添加一个新对象</strong></h3><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/ending.jpg" class="kg-image" alt="ending" width="600" height="400" loading="lazy"></figure><p>我们可以使用 <code>Array.push</code> 在数组的结尾添加一个新的对象。</p><pre><code class="language-js">let car = {
 "color": "red",
 "type": "cabrio",
 "registration": new Date('2016-05-02'),
 "capacity": 2
}
cars.push(car);
</code></pre><h3 id="-array-splice-"><strong>使用 Array.splice 在中间添加一个新对象</strong></h3><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/middle.jpg" class="kg-image" alt="middle" width="600" height="400" loading="lazy"></figure><p>我们可以使用 <code>Array.splice</code> 在数组的中间添加一个新的对象。这个方法非常方便，因为它也可以删除项目。注意其参数：</p><pre><code class="language-js">Array.splice(
  {index where to start},
  {how many items to remove},
  {items to add}
);
</code></pre><p>因此，如果我们要在第五个位置添加红色的 Volkswagen Cabrio，可以这么写：</p><pre><code class="language-js">let car = {
  "color": "red",
  "type": "cabrio",
  "registration": new Date('2016-05-02'),
  "capacity": 2
}
cars.splice(4, 0, car);
</code></pre><h2 id="--1">遍历对象数组</h2><p>让我在这里问你一个问题：为什么要遍历对象数组？我要问的原因是，循环几乎从来不是我们用于实现目的的首选。</p><p>JavaScript 提供了许多功能，可以解决你的问题，而无需通过循环来实现。让我们来看看。</p><h3 id="-array-find-"><strong>使用 Array.find 根据它的值在数组中找到对象</strong></h3><p>如果我们想找到红色的车，可以使用 <code>Array.find</code>。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars-colorred.jpg" class="kg-image" alt="cars-colorred" width="600" height="400" loading="lazy"></figure><pre><code class="language-js">let car = cars.find(car =&gt; car.color === "red");
</code></pre><p>它返回第一个匹配的元素：</p><pre><code class="language-js">console.log(car);
// output:
// {
//   color: 'red',
//   type: 'station wagon',
//   registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
//   capacity: 5
// }
</code></pre><p>也可以搜索多个值：</p><p><code>let car = cars.find(car =&gt; car.color === "red" &amp;&amp; car.type === "cabrio");</code></p><p>在这种情况下，我们可以得到列表中的最后一辆车。</p><h3 id="-array-filter-"><strong>使用 Array.filter 从数组中获取满足一个条件的多个项目</strong></h3><p><code>Array.find</code> 只返回一个对象，如果我们想获取所有红色的车，则需要使用 <code>Array.filter</code>。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars-colorred2.jpg" class="kg-image" alt="cars-colorred2" width="600" height="400" loading="lazy"></figure><pre><code class="language-js">let redCars = cars.filter(car =&gt; car.color === "red");
console.log(redCars);
// output:
// [
//   {
//     color: 'red',
//     type: 'station wagon',
//     registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 5
//   },
//   {
//     color: 'red',
//     type: 'cabrio',
//     registration: 'Sat Mar 03 2012 01:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 2
//   }
// ]
</code></pre><h3 id="-array-map-"><strong>使用 Array.map 转换一个数组的对象</strong></h3><p>我们会经常需要这么做，使用 <code>Array.map</code> 将一个对象数组转换为不同对象的数组。假设我们要根据汽车的大小将其分为三类。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars-sizes.jpg" class="kg-image" alt="cars-sizes" width="600" height="400" loading="lazy"></figure><pre><code class="language-js">let sizes = cars.map(car =&gt; {
  if (car.capacity &lt;= 3){
    return "small";
  }
  if (car.capacity &lt;= 5){
    return "medium";
  }
  return "large";
});
console.log(sizes);
// output:
// ['large','medium','medium', ..., 'small']
</code></pre><p>如果我们需要更多值，也可以创建一个新的对象：</p><pre><code class="language-js">let carsProperties = cars.map(car =&gt; {
 let properties = {
   "capacity": car.capacity,
   "size": "large"
 };
 if (car.capacity &lt;= 5){
   properties['size'] = "medium";
 }
 if (car.capacity &lt;= 3){
   properties['size'] = "small";
 }
 return properties;
});
console.log(carsProperties);
// output:
// [
//   { capacity: 7, size: 'large' },
//   { capacity: 5, size: 'medium' },
//   { capacity: 5, size: 'medium' },
//   { capacity: 2, size: 'small' },
//   ...
// ]
</code></pre><h3 id="-array-foreach-"><strong>使用 Array.forEach 给数组中的每一个对象添加一个属性</strong></h3><p>但是，如果我们也想要汽车对象怎么办？在这种情况下，我们可以增强对象，让它具有新的属性 <code>size</code>。 这是使用 <code>Array.forEach</code> 的一个很好的示例。</p><pre><code class="language-js">cars.forEach(car =&gt; {
 car['size'] = "large";
 if (car.capacity &lt;= 5){
   car['size'] = "medium";
 }
 if (car.capacity &lt;= 3){
   car['size'] = "small";
 }
});
</code></pre><h3 id="-array-sort-"><strong>使用 Array.sort 根据一个属性对数组进行排序</strong></h3><p>完成对象转换后，通常需要以一种方式对它们进行排序。</p><p>通常，排序是基于每个对象都具有的属性的值。我们可以使用 <code>Array.sort</code>，但是我们需要提供一个定义排序机制的函数。</p><p>假设我们要根据汽车载客量对汽车进行降序排序。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars-sort.jpg" class="kg-image" alt="cars-sort" width="600" height="400" loading="lazy"></figure><pre><code class="language-js">let sortedCars = cars.sort((c1, c2) =&gt; (c1.capacity &lt; c2.capacity) ? 1 : (c1.capacity &gt; c2.capacity) ? -1 : 0);
console.log(sortedCars);
// output:
// [
//   {
//     color: 'purple',
//     type: 'minivan',
//     registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 7
//   },
//   {
//     color: 'red',
//     type: 'station wagon',
//     registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 5
//   },
//   ...
// ]
</code></pre><p><code>Array.sort</code> 比较两个对象，如果排序函数的结果为正，则将第一个对象放在第二位。 你可以把排序函数理解成一个问题：应该将第一个对象放在第二位吗？</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/05/sort.png" class="kg-image" alt="sort" width="600" height="400" loading="lazy"></figure><p>当两个对象的比较值相同时，请添加结果为零的情况，以避免不必要的交换。</p><h3 id="-array-every-array-includes-"><strong>使用 Array.every, Array.includes </strong>检查数组中的对象是否满足条件</h3><p>当我们只需要检查对象的特定条件时，<code>Array.every</code> 和 <code>Array.some</code> 就派上用场了。</p><p>汽车列表中有红色敞篷车吗？所有的汽车都能载至少 4 人吗？或者更细致：购物车中是否有特定产品？</p><pre><code class="language-js">cars.some(car =&gt; car.color === "red" &amp;&amp; car.type === "cabrio");
// output: true

cars.every(car =&gt; car.capacity &gt;= 4);
// output: false
</code></pre><p>你可能还记得 <code>Array.includes</code>，它类似于 <code>Array.some</code>，但仅适用于基本类型。</p><h2 id="--2"><strong>小结</strong></h2><p>在本文中，我们介绍了一些基本方法，这些方法可以帮助你创建、操作、转换和循环对象数组。它们应涵盖你会遇到的大多数情况。</p><p>如果你需要使用更高级的功能，可以看一下<a href="https://www.freecodecamp.org/news/data-structures-101-arrays-a-visual-introduction-for-beginners-7f013bcc355a/">这个对数组的详细指南</a>，或者<a href="https://twitter.com/ondrabus">联系我</a>，我会写更多相关文章。</p><p>原文：<a href="https://www.freecodecamp.org/news/javascript-array-of-objects-tutorial-how-to-create-update-and-loop-through-objects-using-js-array-methods/">JavaScript Array of Objects Tutorial – How to Create, Update, and Loop Through Objects Using JS Array Methods</a>，作者：<a href="https://www.freecodecamp.org/news/author/ondrej/">Ondrej Polesny</a></p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 如何使用 .length 检查 JavaScript 数组是否为空 ]]>
                </title>
                <description>
                    <![CDATA[ 使用 JavaScript 编程时，你可能需要知道如何检查数组是否为空。 你可以使用 .length 属性来检查一个数组是否为空。 length 属性设置或返回数组中元素的数量。通过知道数组中元素的数量，你可以知道它是否为空。空数组内部将包含 0 个元素。 让我们来看一些例子。 .length 示例语法 Const myArray = [‘Horses’, ‘Dogs’, ‘Cats’]; 在这里，我们创建一个指向空数组的变量。 使用 length 属性，我们可以检查数组的长度： myArray.length 这将返回 3，因为数组中有 3 个元素。 我们可以通过三种方式使用 .length 检查数组是否为空。 .length 示例一 首先，我们创建一个没有任何元素的新数组。 const arr = [] 现在，我们可以用 .length 检查数组是否为空。 arr.length 这将返回 0，因为数组中有 0 个元素。 .length 示例二 if (arr.length ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/check-if-javascript-array-is-empty-or-not-with-length/</link>
                <guid isPermaLink="false">605b03e6b3d80b05cac656b9</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数组 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chengjun.L ]]>
                </dc:creator>
                <pubDate>Wed, 24 Mar 2021 09:00:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2021/03/road-690087_1920.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>使用 JavaScript 编程时，你可能需要知道如何检查数组是否为空。</p><p>你可以使用 .length 属性来检查一个数组是否为空。</p><p>length 属性设置或返回数组中元素的数量。通过知道数组中元素的数量，你可以知道它是否为空。空数组内部将包含 <code>0</code> 个元素。</p><p>让我们来看一些例子。</p><h2 id="-length-"><strong><strong>.length 示例语法</strong></strong></h2><pre><code class="language-javascript">Const myArray = [‘Horses’, ‘Dogs’, ‘Cats’];</code></pre><p>在这里，我们创建一个指向空数组的变量。</p><p>使用 length 属性，我们可以检查数组的长度：</p><pre><code class="language-javascript">myArray.length</code></pre><p>这将返回 3，因为数组中有 3 个元素。</p><p>我们可以通过三种方式使用 .length 检查数组是否为空。</p><h3 id="-length--1"><strong><strong>.length 示例一</strong></strong></h3><p>首先，我们创建一个没有任何元素的新数组。</p><pre><code class="language-javascript">const arr = []</code></pre><p>现在，我们可以用 <code>.length</code> 检查数组是否为空。</p><pre><code class="language-javascript">arr.length</code></pre><p>这将返回 0，因为数组中有 0 个元素。</p><h3 id="-length--2"><strong><strong>.length 示例二</strong></strong></h3><p><code>if (arr.length === 0) { console.log("Array is empty!") }</code></p><p>如果数组为空，则上面的消息将被打印出来。如果数组中包含元素，则 <code>if</code> 语句中的代码将不会运行。</p><p>下面是使用 .length 检查数组是否为空的第三种方法。</p><h3 id="-length--3"><strong><strong>.length 示例三</strong></strong></h3><p>通过结合使用 length 属性和 JavaScript 中的逻辑 “非” 运算符 “!” 符号，我们可以检查数组是否为空。</p><p><code>!</code> 运算符使表达式取反。也就是说，如果数组为空，我们可以使用它返回 <code>true</code>。</p><p>对于这个示例，我们打开 JavaScript 控制台。点击 Inpsect（检查）-&gt; Console，在 Chrome 中打开控制台。</p><p>首先，创建一个没有元素的数组。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/10/image.png" class="kg-image" alt="image" width="600" height="400" loading="lazy"></figure><p>接下来，让我们使用逻辑“非”运算符以及 .length 属性来测试数组是否为空。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-30-at-5.29.35-PM.png" class="kg-image" alt="Screen-Shot-2020-09-30-at-5.29.35-PM" width="600" height="400" loading="lazy"></figure><p>如果没有使用“非”运算符，则 <code>arr.length</code> 将返回 <code>0</code>。添加了该运算符后，如果其操作结果为 <code>false</code>，则它将返回 <code>true</code>。因为 arr.length 为 <code>0</code> 或 false，所以它返回 <code>true</code>。</p><p>让我们将其与 <code>if</code> 语句一起使用。如果我们的数组为空，则输出一条消息。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-2.png" class="kg-image" alt="image-2" width="600" height="400" loading="lazy"></figure><p>在检查数组是否为空时，通常最好还检查该数组是否确实为数组。</p><p>为什么？</p><p>因为在某些情况下，你可能希望检查数组的长度，但是你却在对其他数据类型进行操作，例如字符串：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-7.png" class="kg-image" alt="image-7" width="600" height="400" loading="lazy"></figure><p>因为 length 属性可以用于其他数据类型，所以最好检查一下数组是否确实是你期望的数组。</p><p>我建议你也使用 <code>Array.isArray()</code> 方法来确认你的数组是一个数组。如果传入的是数组，则此方法将返回 <code>true</code>。</p><p>让我们将此方法添加到示例中。</p><h3 id="-array-isarray-"><strong><strong>如何使用</strong> <strong>Array.isArray() 方法</strong></strong></h3><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-3.png" class="kg-image" alt="image-3" width="600" height="400" loading="lazy"></figure><h2 id="-"><strong><strong>小结</strong></strong></h2><p>在本文中，我们了解到可以在 JavaScript 中以各种方式使用 <code>length</code> 属性来检查数组是否为空。<code>length</code> 属性返回数组中的元素数量。</p><p>我们还了解到，最好在使用 <code>length</code> 属性时也使用 <code>Array.isArray</code> 方法，以检查传递的值是否是你所期望的数组。</p><p>原文：<a href="https://www.freecodecamp.org/news/check-if-javascript-array-is-empty-or-not-with-length/">How to Check if a JavaScript Array is Empty or Not with .length</a>，作者：<a href="https://www.freecodecamp.org/news/author/madisonkanna/">Madison Kanna</a><br></p> ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
