<?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[ Suxiong - 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[ Suxiong - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/chinese/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 04:46:52 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/chinese/news/author/suxiong/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ 在 JavaScript 中如何过滤数组和对象 ]]>
                </title>
                <description>
                    <![CDATA[ 在创建一个动态交互项目时，你需要添加一些交互的特性。比如说，当用户点击按钮时会过滤一个长数组。 你也可能需要操作一个大数组，要求其只返回符合特定条件的元素。 在这篇文章中，你将会学习在 JavaScript 中过滤数组的两种主要方法。你也会学到如何过滤对象中的数组，并且返回一个过滤后的新数组。 如何通过for 循环过滤数组 在 2015 年 ES6 诞生之前，许多开发者通过 for 循环方法去解决几乎所有的数组操作问题。但是代码变得十分冗长且难以理解，因此出现了很多单独的 JavaScript 方法，例如 filter()  方法（你将很快学习到）。 但是首先，为了完整性，我们看一下使用 for 循环如何做。 假设你有一个含对象的数组，对象中包含用户的信息，例如名字，年龄和职业。你能决定过滤那些年龄符合特定条件的用户。 let users = [     { name: 'John', age: 25, occupation: 'gardener' },     { name: 'Lenny', age: 51, occupation: 'programmer' ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/filter-arrays-in-javascript/</link>
                <guid isPermaLink="false">63ff45ea0687e3060be26f8e</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Suxiong ]]>
                </dc:creator>
                <pubDate>Wed, 01 Mar 2023 12:40:31 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2023/03/pexels-christina-morillo-1181675.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p data-test-label="translation-intro">
        <strong>原文：</strong> <a href="https://www.freecodecamp.org/news/filter-arrays-in-javascript/" target="_blank" rel="noopener noreferrer" data-test-label="original-article-link">How to Filter an Array in JavaScript – JS Filtering for Arrays and Objects</a>
      </p><!--kg-card-begin: markdown--><p>在创建一个动态交互项目时，你需要添加一些交互的特性。比如说，当用户点击按钮时会过滤一个长数组。</p>
<p>你也可能需要操作一个大数组，要求其只返回符合特定条件的元素。</p>
<p>在这篇文章中，你将会学习在 JavaScript 中过滤数组的两种主要方法。你也会学到如何过滤对象中的数组，并且返回一个过滤后的新数组。</p>
<h2 id="for">如何通过<code>for 循环</code>过滤数组</h2>
<p>在 2015 年 ES6 诞生之前，许多开发者通过 for 循环方法去解决几乎所有的数组操作问题。但是代码变得十分冗长且难以理解，因此出现了很多单独的 JavaScript 方法，例如 <code>filter()</code> 方法（你将很快学习到）。</p>
<p>但是首先，为了完整性，我们看一下使用 for 循环如何做。</p>
<p>假设你有一个含对象的数组，对象中包含用户的信息，例如名字，年龄和职业。你能决定过滤那些年龄符合特定条件的用户。</p>
<pre><code class="language-js">let users = [
    { name: 'John', age: 25, occupation: 'gardener' },
    { name: 'Lenny', age: 51, occupation: 'programmer' },
    { name: 'Andrew', age: 43, occupation: 'teacher' },
    { name: 'Peter', age: 81, occupation: 'teacher' },
    { name: 'Anna', age: 47, occupation: 'programmer' },
    { name: 'Albert', age: 76, occupation: 'programmer' },
]
</code></pre>
<p>现在，你可以过滤这个对象数组，并返回 <code>age</code> 大于 <code>40</code>，<code>occupation</code> 为 <code>programmer</code>的新数组。</p>
<pre><code class="language-js">let filteredUsers = [];
for (let i= 0; i&lt;users.length; i++) {
    if (users[i].age &gt; 40 &amp;&amp; users[i].occupation === 'programmer' ) {
        filteredUsers = [...filteredUsers, users[i]];
    }
}
console.log(filteredUsers);
</code></pre>
<p>将会返回包含三个符合条件用户的新数组。</p>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_A2A56A7C05733A13745945CF4C6950EBC758CD93042A33CBFFD44710AB9E7883_1676527392206_image.png" alt="s_A2A56A7C05733A13745945CF4C6950EBC758CD93042A33CBFFD44710AB9E7883_1676527392206_image" width="600" height="400" loading="lazy"></p>
<p>现在，结果正确。但有一个更好的方法去过滤数组就是使用 ES6 filter()方法。</p>
<h2 id="filter">如何通过 <code>filter</code>方法过滤数组</h2>
<p><code>filter()</code> 方法是一个 ES6 方法，其提供了更干净的语法去过滤数组。它返回了一个新的数组，而且也并没有更改原数组。</p>
<pre><code class="language-js">// Syntax
myArray.filter(callbackFn)
</code></pre>
<p>在 callback 函数中，你可以访问每一个元素，元素的 <code>index</code> 以及原数组本身：</p>
<pre><code class="language-js">myArray.filter((element, index, array) =&gt; { /* ... */ })
</code></pre>
<p>现在让我们展示相同的例子去通过 <code>age</code> 和 <code>occupation</code> 去过滤用户数组。</p>
<pre><code class="language-js">let filteredUsers = users.filter((user) =&gt; {
    return user.age &gt; 40 &amp;&amp; user.occupation === 'programmer';
});

console.log(filteredUsers);
</code></pre>
<p>这将会返回一个精确的输出，但你注意到你的代码十分到干净。同样重要的是，你能够将代码重写为一行，并且除掉 <code>return</code> 状态。</p>
<pre><code class="language-js">let filteredUsers = users.filter(user =&gt; user.age &gt; 40 &amp;&amp; user.occupation === 'programmer');
console.log(filteredUsers);
</code></pre>
<p>两个代码块都可以输出过滤后的用户：</p>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_A2A56A7C05733A13745945CF4C6950EBC758CD93042A33CBFFD44710AB9E7883_1676527392206_image.png" alt="s_A2A56A7C05733A13745945CF4C6950EBC758CD93042A33CBFFD44710AB9E7883_1676527392206_image" width="600" height="400" loading="lazy"></p>
<p>这个 filter 方法能够不需要创建过多的变量而执行更多的操作，因为它能够链式调用其他函数方法。</p>
<p>例如，你能将过滤后的数组分类，并且返回只包含他们名字的数组：</p>
<pre><code class="language-js">let filteredUserNames = users.filter(user =&gt; user.age &gt; 40 &amp;&amp; user.occupation === 'programmer')
    .sort((a, b) =&gt; a.age - b.age)
    .map(user =&gt; user.name);

console.log(filteredUserNames); // ['Anna', 'Lenny', 'Albert']
</code></pre>
<p>使用 JavaScript filter()方法在 JavaScript 中去过滤数组还能做很多事情。你能够在 <a href="https://www.freecodecamp.org/news/javascript-array-filter-tutorial-how-to-iterate-through-elements-in-an-array/">JavaScript Array.filter() 教程</a>了解更多关于 JavaScript filter 方法，并且你也能了解<a href="https://www.freecodecamp.org/chinese/news/find-vs-filter-javascript/">在 JavaScript 中 find() 和 filter() 方法的区别</a>。</p>
<h2 id="javascript">在 JavaScript 中如何过滤一个对象</h2>
<p>JavaScript 中的对象不像数组和字符串一样可迭代（你不能遍历它们）。这意味着你不能直接对一个对象使用 <code>filter()</code>、<code>for</code> 循环方法或者任何遍历方法。那么该如何在 JavaScript 中过滤一个对象呢？</p>
<p>你可以通过使用对象的静态方法，如 <code>object .keys()</code> ， <code>Object.values()</code> 或 <code>Object.entries()</code>，将对象转换为数组来实现这一点。然后可以使用 filter()方法对数组进行筛选，并返回一个由筛选过的元素组成的新数组。</p>
<p>假设有一个对象保存用户的详细信息，如姓名、年龄和职业。这些对象静态方法可以以数组的形式返回键、值或每个键-值对。</p>
<pre><code class="language-js">const userDetails = {
    firstName: "Jane",
    lastName: "Daniels",
    userName: "jane.daniels",
    email: "jane.daniels@example.com",
    comapny: "Example Inc.",
    address: "1234 Example Street",
    age : 25,
    hobby: "Singing"
};

let keysArray = Object.keys(userDetails);

console.log(keysArray);
</code></pre>
<p>这将返回一个对象键的数组：</p>
<pre><code class="language-js">['firstName', 'lastName', 'userName', 'email', 'comapny', 'address', 'age', 'hobby']
</code></pre>
<p>你现在可以使用 <code>filter()</code> 方法对数组进行过滤，并返回一个由过滤后的元素组成的新数组：</p>
<pre><code class="language-js">let filteredKeys = keysArray.filter(key =&gt; key.length &gt; 5);

console.log(filteredKeys);
</code></pre>
<p>这将返回一个长度大于 5 的键数组：</p>
<pre><code class="language-js">['firstName', 'lastName', 'userName', 'comapny', 'address', 'hobby']
</code></pre>
<p>但是，你肯定希望执行更有用的筛选操作。例如，你可以从一个大对象中筛选包含名称的对象键-值对。然后你可以先获取键，过滤它们，并使用 <code>reduce()</code> 方法将过滤后的键<code>减少</code>为具有过滤后的键及其值的对象：</p>
<pre><code class="language-js">const userDetails = {
    firstName: "Jane",
    lastName: "Daniels",
    userName: "jane.daniels",
    email: "jane.daniels@example.com",
    comapny: "Example Inc.",
    address: "1234 Example Street",
    age : 25,
    hobby: "Singing"
};

const userNames = Object.keys(userDetails)
    .filter((key) =&gt; key.includes("Name"))
    .reduce((object, key) =&gt; {
        return Object.assign(object, {
          [key]: userDetails[key]
        });
  }, {});

console.log(userNames);
</code></pre>
<p>这将返回一个包含筛选键及其值的对象：</p>
<pre><code class="language-js">{
    firstName: "Jane",
    lastName: "Daniels",
    userName: "jane.daniels"
}
</code></pre>
<h2 id="">总结</h2>
<p>在本文中，你已经学习了如何使用<code>for</code>循环和<code>filter()</code>方法在 JavaScript 中筛选数组。<code>filter()</code>为 JavaScript 中的数组过滤提供了更好的语法。</p>
<p>你还学习了如何通过将对象转换为数组并使用 filter()方法在 JavaScript 中筛选对象。</p>
<p>感谢阅读，happy coding!</p>
<p>你可以通过<a href="https://joelolawanle.com/contents">访问我的网站</a>访问我的 188 篇文章。你还可以通过搜索去浏览我特定的文章。</p>
<!--kg-card-end: markdown--> ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
