苏儿 發表於 2026-1-8 08:30:23

JavaScript数组方法push()、forEach()、filter()、sort()实战教程

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li><a href="#_label0">前言</a></li><li><a href="#_label1">一、push():给数组&ldquo;尾部追加&rdquo;元素</a></li><ul class="second_class_ul"><li><a href="#_lab2_1_0">核心功能</a></li><li><a href="#_lab2_1_1">适用场景</a></li><li><a href="#_lab2_1_2">可运行代码案例</a></li><li><a href="#_lab2_1_3">常见错误与解决方案</a></li></ul><li><a href="#_label2">二、forEach():遍历数组的&ldquo;万能工具&rdquo;</a></li><ul class="second_class_ul"><li><a href="#_lab2_2_4">核心功能</a></li><li><a href="#_lab2_2_5">适用场景</a></li><li><a href="#_lab2_2_6">可运行代码案例</a></li><li><a href="#_lab2_2_7">常见错误与解决方案</a></li></ul><li><a href="#_label3">三、filter():筛选数组的&ldquo;精准过滤器&rdquo;</a></li><ul class="second_class_ul"><li><a href="#_lab2_3_8">核心功能</a></li><li><a href="#_lab2_3_9">适用场景</a></li><li><a href="#_lab2_3_10">可运行代码案例</a></li><li><a href="#_lab2_3_11">常见错误与解决方案</a></li></ul><li><a href="#_label4">四、sort():排序数组的&ldquo;灵活排序器&rdquo;</a></li><ul class="second_class_ul"><li><a href="#_lab2_4_12">核心功能</a></li><li><a href="#_lab2_4_13">适用场景</a></li><li><a href="#_lab2_4_14">可运行代码案例</a></li><li><a href="#_lab2_4_15">常见错误与解决方案</a></li></ul><li><a href="#_label5">五、总结</a></li><ul class="second_class_ul"></ul></ul></div><p class="maodian"><a name="_label0"></a></p><h2>前言</h2>
<p>你是否在处理 JavaScript 数组数据时,不知道该用哪个方法添加元素、遍历数据、筛选内容或排序?这篇教程将通过具体场景、可运行代码,以及常见错误与解决方案,帮你彻底掌握 <code>push()</code>、<code>forEach()</code>、<code>filter()</code>、<code>sort()</code> 四个核心数组方法的功能与实际用法,学完就能直接在项目中落地。</p>
<p class="maodian"><a name="_label1"></a></p><h2>一、push():给数组&ldquo;尾部追加&rdquo;元素</h2>
<p class="maodian"><a name="_lab2_1_0"></a></p><p class="maodian"><a name="_lab2_2_4"></a></p><p class="maodian"><a name="_lab2_3_8"></a></p><p class="maodian"><a name="_lab2_4_12"></a></p><h3>核心功能</h3>
<p><code>push()</code> 方法用于<strong>向数组的末尾添加一个或多个元素</strong>,并且会返回更新后数组的长度(注意:不是更新后的数组本身)。它会直接修改原始数组,这是一个重要特性。</p>
<p class="maodian"><a name="_lab2_1_1"></a></p><p class="maodian"><a name="_lab2_2_5"></a></p><p class="maodian"><a name="_lab2_3_9"></a></p><p class="maodian"><a name="_lab2_4_13"></a></p><h3>适用场景</h3>
<ul><li>向列表中追加新数据(如用户提交表单后,将新用户信息加入用户列表)</li><li>批量补充数据到数组尾部</li><li>动态构建数组(逐步添加元素)</li></ul>
<p class="maodian"><a name="_lab2_1_2"></a></p><p class="maodian"><a name="_lab2_2_6"></a></p><p class="maodian"><a name="_lab2_3_10"></a></p><p class="maodian"><a name="_lab2_4_14"></a></p><h3>可运行代码案例</h3>
<div class="jb51code"><pre class="brush:js;">// 1. 基础用法:添加单个元素
const fruitList = ['苹果', '香蕉', '橙子'];
// 调用push(),添加单个元素
const newLength1 = fruitList.push('葡萄');
console.log('添加单个元素后的数据:', fruitList); // 输出:['苹果', '香蕉', '橙子', '葡萄']
console.log('更新后数组长度:', newLength1); // 输出:4

// 2. 进阶用法:添加多个元素
const numberArr = ;
// 调用push(),批量添加多个元素(用逗号分隔)
const newLength2 = numberArr.push(4, 5, 6);
console.log('添加多个元素后的数据:', numberArr); // 输出:
console.log('更新后数组长度:', newLength2); // 输出:6

// 3. 实战场景:用户列表追加新用户
const userList = [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 28 }
];
// 新用户数据
const newUser = { id: 3, name: '王五', age: 30 };
// 追加新用户
userList.push(newUser);
console.log('追加新用户后的列表:', userList);
// 输出:[{ id:1, ... }, { id:2, ... }, { id:3, ... }]
</pre></div>
<p class="maodian"><a name="_lab2_1_3"></a></p><p class="maodian"><a name="_lab2_2_7"></a></p><p class="maodian"><a name="_lab2_3_11"></a></p><p class="maodian"><a name="_lab2_4_15"></a></p><h3>常见错误与解决方案</h3>
<table><thead><tr><th>常见错误</th><th>错误描述</th><th>解决方案</th></tr></thead><tbody><tr><td>错误1:误将push()返回值当作更新后的数组</td><td>代码示例:<code>const newArr = fruitList.push(&#39;葡萄&#39;);</code>,此时<code>newArr</code>是数字4(数组长度),而非数组本身,导致后续操作报错</td><td>1. 先调用<code>push()</code>修改原始数组;2. 若需保留原数组,先复制原数组(<code>const newArr = [...fruitList]</code>),再对复制后的数组调用<code>push()</code>;3. 避免直接接收<code>push()</code>的返回值作为数组使用</td></tr><tr><td>错误2:给非数组类型调用push()</td><td>代码示例:<code>const str = &#39;abc&#39;; str.push(&#39;d&#39;);</code>,字符串不是数组,没有<code>push()</code>方法,报错<code>Uncaught TypeError: str.push is not a function</code></td><td>1. 先确认目标变量是数组类型(可用<code>Array.isArray(obj)</code>判断);2. 若为类数组/字符串,先转换为数组(字符串转数组:<code>Array.from(str)</code>,类数组转数组:<code>[...arguments]</code>)</td></tr><tr><td>错误3:批量添加数组时,直接传入数组导致二维数组</td><td>代码示例:<code>const arr = ; arr.push();</code>,结果为<code>]</code>(非预期的<code></code>)</td><td>1. 使用扩展运算符:<code>arr.push(...)</code>,将数组展开为单个元素后追加;2. 也可使用<code>concat()</code>方法(<code>const newArr = arr.concat()</code>,不修改原数组)</td></tr></tbody></table>
<p class="maodian"><a name="_label2"></a></p><h2>二、forEach():遍历数组的&ldquo;万能工具&rdquo;</h2>
<h3>核心功能</h3>
<p><code>forEach()</code> 方法用于<strong>遍历数组的每一个元素</strong>,并对每个元素执行你指定的回调函数。它没有返回值(返回 <code>undefined</code>),仅用于执行遍历操作,可选择性地修改原始数组(取决于回调函数内的操作)。</p>
<h3>适用场景</h3>
<ul><li>遍历数组并打印/展示所有元素</li><li>对数组中每个元素执行统一操作(如格式化数据、累加计算)</li><li>无需返回新数组,仅需遍历处理的场景</li></ul>
<h3>可运行代码案例</h3>
<div class="jb51code"><pre class="brush:js;">// 1. 基础用法:遍历数组并打印每个元素
const animalArr = ['老虎', '大象', '熊猫', '猴子'];
console.log('动物列表遍历结果:');
animalArr.forEach((animal, index) =&gt; {
// 回调函数参数:item(当前元素)、index(当前索引,可选)、array(原数组,可选)
console.log(`索引${index}:${animal}`);
});
// 输出:
// 索引0:老虎
// 索引1:大象
// 索引2:熊猫
// 索引3:猴子

// 2. 进阶用法:遍历数组并累加计算
const scoreArr = ;
let totalScore = 0;
// 遍历分数数组,累加总分
scoreArr.forEach(score =&gt; {
totalScore += score;
});
const averageScore = totalScore / scoreArr.length;
console.log('总分:', totalScore); // 输出:431
console.log('平均分:', averageScore); // 输出:86.2

// 3. 实战场景:格式化数组元素(给商品名称添加前缀)
const productList = ['手机', '电脑', '平板', '耳机'];
const formatProductList = [];
// 遍历商品列表,格式化后存入新数组
productList.forEach(product =&gt; {
formatProductList.push(`热销-${product}`);
});
console.log('格式化后的商品列表:', formatProductList);
// 输出:['热销-手机', '热销-电脑', '热销-平板', '热销-耳机']
</pre></div>
<h3>常见错误与解决方案</h3>
<table><thead><tr><th>常见错误</th><th>错误描述</th><th>解决方案</th></tr></thead><tbody><tr><td>错误1:试图用return终止forEach()遍历</td><td>代码示例:<code>animalArr.forEach(animal =&gt; { if (animal === &#39;熊猫&#39;) return; console.log(animal); })</code>,<code>return</code>仅跳过当前循环,无法终止整个遍历,仍会打印&ldquo;猴子&rdquo;</td><td>1. 若需终止遍历,放弃<code>forEach()</code>,使用<code>for</code>循环/<code>for...of</code>循环(可通过<code>break</code>终止);2. 若仅需跳过部分元素,<code>return</code>可正常使用</td></tr><tr><td>错误2:误将forEach()当作有返回值的方法</td><td>代码示例:<code>const newArr = productList.forEach(p =&gt; </code>热销-${p}<code>);</code>,<code>newArr</code>值为<code>undefined</code>,非预期数组</td><td>1. 先创建空数组,在<code>forEach()</code>回调内用<code>push()</code>存入处理后的数据(如案例3);2. 直接使用<code>map()</code>方法(专门用于返回处理后的新数组,更简洁)</td></tr><tr><td>错误3:遍历中修改数组长度导致遍历不完整/死循环</td><td>代码示例:<code>const arr = ; arr.forEach(item =&gt; { arr.push(item * 2); })</code>,会无限追加元素导致死循环;若删除元素则会跳过部分元素</td><td>1. 遍历前先复制数组(<code>[...arr]</code>),遍历复制后的数组,修改原始数组;2. 避免在<code>forEach()</code>中直接增删原始数组的元素,防止破坏遍历结构</td></tr><tr><td>错误4:回调函数中使用this指向丢失(普通函数写法)</td><td>代码示例:<code>const obj = { num: 10 }; arr.forEach(function(item) { console.log(this.num); })</code>,此时<code>this</code>指向<code>window</code>(非严格模式),输出<code>undefined</code></td><td>1. 使用箭头函数(不绑定自身<code>this</code>,继承外部上下文):<code>arr.forEach(item =&gt; console.log(this.num))</code>;2. 传入<code>thisArg</code>作为<code>forEach()</code>第二个参数:<code>arr.forEach(function(item) {}, obj)</code></td></tr></tbody></table>
<p class="maodian"><a name="_label3"></a></p><h2>三、filter():筛选数组的&ldquo;精准过滤器&rdquo;</h2>
<h3>核心功能</h3>
<p><code>filter()</code> 方法用于<strong>根据指定条件筛选数组元素</strong>,它会返回一个全新的数组(包含所有满足条件的元素),不会修改原始数组。如果没有满足条件的元素,会返回一个空数组。</p>
<h3>适用场景</h3>
<ul><li>按条件筛选数据(如筛选大于10的数字、筛选成年用户)</li><li>排除数组中的无效数据(如筛选非空字符串、排除值为null的元素)</li><li>多条件组合筛选(如筛选年龄在20-30岁之间的女性用户)</li></ul>
<h3>可运行代码案例</h3>
<div class="jb51code"><pre class="brush:js;">// 1. 基础用法:筛选满足单一条件的元素
const numArr = ;
// 筛选大于20的数字
const bigNumArr = numArr.filter(num =&gt; {
return num &gt; 20;
});
console.log('原始数组:', numArr); // 输出:
console.log('大于20的数字数组:', bigNumArr); // 输出:

// 2. 进阶用法:多条件组合筛选
const studentList = [
{ name: '小明', gender: '男', age: 18, score: 90 },
{ name: '小红', gender: '女', age: 17, score: 95 },
{ name: '小刚', gender: '男', age: 19, score: 85 },
{ name: '小丽', gender: '女', age: 18, score: 92 },
{ name: '小亮', gender: '男', age: 17, score: 88 }
];
// 筛选:女性 &amp;&amp; 年龄18岁 &amp;&amp; 分数大于90
const targetStudents = studentList.filter(student =&gt; {
return student.gender === '女' &amp;&amp; student.age === 18 &amp;&amp; student.score &gt; 90;
});
console.log('满足条件的学生:', targetStudents); // 输出:[{ name: '小丽', ... }]

// 3. 实战场景:排除无效数据(筛选非空、非undefined的用户名)
const userNameList = ['张三', '', '李四', undefined, '王五', null, '赵六'];
// 筛选有效用户名(排除空字符串、undefined、null)
const validUserNameList = userNameList.filter(name =&gt; {
return name !== '' &amp;&amp; name !== undefined &amp;&amp; name !== null;
});
console.log('原始用户名列表:', userNameList);
console.log('有效用户名列表:', validUserNameList); // 输出:['张三', '李四', '王五', '赵六']
</pre></div>
<h3>常见错误与解决方案</h3>
<table><thead><tr><th>常见错误</th><th>错误描述</th><th>解决方案</th></tr></thead><tbody><tr><td>错误1:忘记在回调函数中返回判断条件</td><td>代码示例:<code>const bigNumArr = numArr.filter(num =&gt; { num &gt; 20; })</code>,回调函数无返回值(默认返回<code>undefined</code>),最终返回空数组</td><td>1. 显式添加<code>return</code>关键字(如案例1);2. 使用箭头函数简写(省略大括号,自动返回表达式结果):<code>numArr.filter(num =&gt; num &gt; 20)</code></td></tr><tr><td>错误2:混淆filter()与forEach(),用filter()执行无返回值的操作</td><td>代码示例:<code>numArr.filter(num =&gt; console.log(num))</code>,虽能遍历打印,但会额外生成无意义的空数组,造成性能浪费</td><td>1. 仅当需要筛选并返回新数组时使用<code>filter()</code>;2. 若仅需遍历执行操作(无返回数组需求),使用<code>forEach()</code>/<code>for</code>循环</td></tr><tr><td>错误3:筛选引用类型数据时,误判&ldquo;空对象/空数组&rdquo;为无效数据</td><td>代码示例:<code>const arr = [{}, [], 123]; const newArr = arr.filter(item =&gt; item)</code>,<code>{}</code>和<code>[]</code>为真值,会被保留,若需排除空对象/数组则筛选失败</td><td>1. 排除空对象:判断对象自身属性数量 <code>Object.keys(item).length &gt; 0</code>;2. 排除空数组:判断数组长度 <code>item.length &gt; 0</code>;3. 组合判断:<code>arr.filter(item =&gt; !(Array.isArray(item) &amp;&amp; item.length === 0) &amp;&amp; !(typeof item === &#39;object&#39; &amp;&amp; item !== null &amp;&amp; Object.keys(item).length === 0))</code></td></tr><tr><td>错误4:多条件筛选时逻辑运算符使用错误(&amp;&amp;与||混淆)</td><td>代码示例:筛选&ldquo;年龄18或19岁的女生&rdquo;,误写为<code>student.gender === &#39;女&#39; &amp;&amp; student.age === 18 &amp;&amp; student.age === 19</code>,无满足条件的元素,返回空数组</td><td>1. 明确逻辑关系:&ldquo;且&rdquo;用<code>&amp;&amp;</code>,&ldquo;或&rdquo;用`</td></tr></tbody></table>
<p class="maodian"><a name="_label4"></a></p><h2>四、sort():排序数组的&ldquo;灵活排序器&rdquo;</h2>
<h3>核心功能</h3>
<p><code>sort()</code> 方法用于<strong>对数组元素进行排序</strong>,默认情况下按「字符串Unicode编码」升序排列(注意:这是容易踩坑的点),它会直接修改原始数组。同时支持传入自定义比较函数,实现数字升序/降序、对象属性排序等灵活需求。</p>
<h3>适用场景</h3>
<ul><li>数字数组升序/降序排序(如分数从高到低排序)</li><li>字符串数组排序(如按姓名拼音首字母排序)</li><li>对象数组按指定属性排序(如按用户年龄、商品价格排序)</li></ul>
<h3>可运行代码案例</h3>
<div class="jb51code"><pre class="brush:js;">// 1. 注意点:默认排序(字符串Unicode编码,不适合数字排序)
const defaultNumArr = ;
defaultNumArr.sort();
console.log('数字默认排序结果:', defaultNumArr); // 输出:(不符合预期)

// 2. 基础用法:数字数组升序/降序排序(传入自定义比较函数)
const sortNumArr = ;
// 数字升序排序:a - b
sortNumArr.sort((a, b) =&gt; a - b);
console.log('数字升序排序:', sortNumArr); // 输出:

// 数字降序排序:b - a
sortNumArr.sort((a, b) =&gt; b - a);
console.log('数字降序排序:', sortNumArr); // 输出:

// 3. 进阶用法:对象数组按指定属性排序
const goodsList = [
{ name: '手机', price: 4999 },
{ name: '电脑', price: 7999 },
{ name: '平板', price: 2999 },
{ name: '耳机', price: 999 }
];
// 按商品价格升序排序(从便宜到贵)
goodsList.sort((a, b) =&gt; a.price - b.price);
console.log('按价格升序排序的商品:', goodsList);
// 输出:[{ name: '耳机', price:999 }, { name: '平板', price:2999 }, ...]

// 按商品价格降序排序(从贵到便宜)
goodsList.sort((a, b) =&gt; b.price - a.price);
console.log('按价格降序排序的商品:', goodsList);
// 输出:[{ name: '电脑', price:7999 }, { name: '手机', price:4999 }, ...]

// 4. 实战场景:字符串数组排序(按姓名排序)
const nameList = ['Zhang San', 'Li Si', 'Wang Wu', 'Zhao Liu'];
// 按字符串Unicode编码升序排序(英文姓名适用)
nameList.sort();
console.log('姓名升序排序:', nameList); // 输出:['Li Si', 'Wang Wu', 'Zhang San', 'Zhao Liu']
</pre></div>
<h3>常见错误与解决方案</h3>
<table><thead><tr><th>常见错误</th><th>错误描述</th><th>解决方案</th></tr></thead><tbody><tr><td>错误1:直接对数字数组使用默认sort()排序,结果不符合预期</td><td>代码示例:<code>const arr = ; arr.sort();</code>,结果为<code></code>,而非数字升序<code></code></td><td>1. 传入自定义比较函数实现数字排序:升序<code>(a,b) =&gt; a - b</code>,降序<code>(a,b) =&gt; b - a</code>(如案例2);2. 牢记:默认sort()按字符串Unicode编码排序,不适用数字场景</td></tr><tr><td>错误2:对象数组排序时,直接比较对象而非对象的属性</td><td>代码示例:<code>goodsList.sort((a,b) =&gt; a - b)</code>,a和b是对象,无法直接相减,报错<code>NaN</code>,排序失败</td><td>1. 排序时指定对象的具体属性:<code>(a,b) =&gt; a.price - b.price</code>(如案例3);2. 若属性是字符串,可直接传入属性名(或使用<code>localeCompare()</code>优化中文排序)</td></tr><tr><td>错误3:忽略sort()会修改原始数组,导致原数组数据丢失</td><td>代码示例:需要保留原始数组,却直接调用<code>arr.sort()</code>,原数组被篡改</td><td>1. 排序前先复制原始数组(使用扩展运算符<code>[...arr]</code>、<code>Array.from(arr)</code>或<code>arr.slice()</code>);2. 对复制后的数组执行排序:<code>const sortedArr = [...arr].sort((a,b) =&gt; a - b)</code></td></tr><tr><td>错误4:中文字符串排序时,默认sort()结果混乱(按Unicode编码,非拼音/笔画)</td><td>代码示例:<code>const chineseArr = [&#39;张三&#39;, &#39;李四&#39;, &#39;王五&#39;]; chineseArr.sort();</code>,排序结果可能不符合中文使用习惯</td><td>1. 使用<code>localeCompare()</code>方法优化中文排序:<code>chineseArr.sort((a,b) =&gt; a.localeCompare(b, &#39;zh-CN&#39;))</code>;2. 该方法支持按拼音、笔画排序(可配置额外参数)</td></tr></tbody></table>
<p class="maodian"><a name="_label5"></a></p><h2>五、总结</h2>
<ol><li><strong>push()</strong>:尾部追加元素,修改原始数组,返回新长度;避坑重点:不接收返回值作为数组,批量添加用扩展运算符。</li><li><strong>forEach()</strong>:遍历所有元素,无返回值;避坑重点:无法用<code>return</code>终止遍历,不用于生成新数组。</li><li><strong>filter()</strong>:条件筛选元素,返回新数组,不修改原数组;避坑重点:必须返回判断条件,区分逻辑运算符<code>&amp;&amp;</code>与<code>||</code>。</li><li><strong>sort()</strong>:数组排序,修改原始数组,默认按字符串编码排序;避坑重点:数字排序传自定义比较函数,对象排序比较具体属性,需保留原数组先复制。</li></ol>
<p>这四个方法是 JavaScript 数组操作的基础,掌握它们的功能、场景及避坑技巧后,能高效处理大部分数组数据处理需求,所有代码均可直接复制到浏览器控制台或 Node.js 环境中运行验证。</p>
頁: [1]
查看完整版本: JavaScript数组方法push()、forEach()、filter()、sort()实战教程