代码分析:

  1. 首先创建了一个包含6个字符串元素的数组 names。
  2. 使用 unshift 方法向数组的开头添加一个元素,添加的元素是字符串 'lucy'。此时数组变为 ['lucy','smith','tom','jerry','ken','alens','bruce lee']。
  3. 使用 console.log 打印输出数组,输出结果为 ['lucy','smith','tom','jerry','ken','alens','bruce lee']。
  4. 使用 unshift 方法向数组的开头添加多个元素,添加的元素是字符串 'jack' 和 'yuehan'。此时数组变为 ['jack','yuehan','lucy','smith','tom','jerry','ken','alens','bruce lee']。
  5. 使用 console.log 打印输出数组,输出结果为 ['jack','yuehan','lucy','smith','tom','jerry','ken','alens','bruce lee']。

向数组末尾添加元素的代码: 可以使用 push 方法向数组末尾添加元素。例如,要向数组 names 末尾添加一个元素,可以使用以下代码: names.push('newElement');

JavaScript 数组操作:向数组开头和末尾添加元素

原文地址: https://www.cveoy.top/t/topic/qoRR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录