数组添加元素

date
Mar 12, 2023
slug
js-add-array
status
Published
tags
JavaScript数据结构与算法
Array
JavaScript
summary
JavaScript Add Array
type
Post

添加元素

在数组末尾插入元素

let nums = [0,1,2,3,4,5,6,7,8,9];
  1. 把值赋给数组中最后一个空位上的元素
    1. nums[nums.length] = 10;
      ​ 注:在JavaScript中,数组是一个可以修改的对象。如果添加元素,它就会动态增长。在C和Java等其他语言中,想添加元素就要创建一个全新的数组,不能简单地往其中添加所需元素(可能会造成数组越界)
  1. 使用push
    1. 添加任意个元素
      nums.push(11);nums.push(12,13);

在数组开头插入元素

​ 腾出数组里第一个元素的位置,把所有的元素向右移动一位。循环数组中的元素,从最后一位开始,将对应的前一个元素( i - 1)的值赋给它( i ),依次处理,最后把我们想要的值赋给第一个位置。
let nums = [0,1,2,3,4,5,6,7,8,9];
Array.prototype.insertFirstPosition = function(value)
{
    for(let i = this.length; i >= 0; i--)
        {
            this[i] = this[i - 1];
        }
    this[0] = value;
}
nums.insertFirstPosition(-1);
console.log(nums);//[-1,0,1,2,3,4,5,6,7,8,9]
操作过程如下:
notion image

使用unshift方法

nums.unshift(-2);nums.unshift(-4,-3);
 

© shallrise 2025