Home >Web Front-end >JS Tutorial >JavaScript Arrays: How to Create and Manipulate

JavaScript Arrays: How to Create and Manipulate

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-18 10:50:10564browse

In-depth and easy-to-understand JavaScript array: Detailed explanation of creation and operation

JavaScript Arrays: How to Create and Manipulate

Core points

  • JavaScript array has length attributes, can be operated, and has a numbered attribute with a name range of between 0 and 4294967294 (inclusive). JavaScript does not support associative arrays.
  • The JavaScript arrays are created in various ways, and it is recommended to use array literals to create new arrays. The array can be intensive (length equals the number of numbered attributes) or sparse (length greater than the number of numbered attributes).
  • The length of the JavaScript array can be changed. If the new length is set less than the current length, any numbered attributes in the array that are positioned greater than the new length will be removed.
  • JavaScript provides methods to add, remove, and replace entries in an array. Methods to add entries include push, unshift and splice; methods to remove entries include pop, shift and splice.

Learn how to manipulate JavaScript arrays. We will cover the array creation process, changing array length, and adding, removing, and replacing entries. The Array attribute of an object is a property that many newbies in JavaScript do not understand. Many people mistakenly believe that length tells you exactly how many entries there are in an array, and this only holds true for some arrays. Some beginners don't even realize that length is a writable property of an array. To clarify how the length attribute works, let's see what happens when we change its value ourselves or run an operation that also causes a length change. Let's start from scratch. JavaScript arrays have an attribute named length and can be optionally given a numbered attribute whose name is between 0 and 4294967294 (inclusive). It also has some methods for manipulating properties, some of which we will look at when examining how length properties work. Note that JavaScript does not support associative arrays, so while you can add named properties to the array, they do not form part of the array and will be ignored by all array methods. They also do not affect length. To make it easier to show what happens to array properties when working with various statements, we will run the following function after each piece of code. This records the length of the array and all numbered properties to the browser's console. length

<code class="language-javascript">var test = function(array) {
  console.log('length:'+ array.length);
  array.forEach(function(element, index, array) {
    console.log(index + ':' + element);
  });
};</code>

This article was reviewed by Chris Perry and Marcello La Rocca. Thanks to all the peer reviewers of SitePoint to make the content of SitePoint perfect!

Create an array in JavaScript

We will first look at different ways to create arrays in JavaScript. The arrays created by the first two examples are only set in length and have no numbered entries at all. The last two examples create a numbered entry from 0 to minus length 1. An array with a length greater than the numbered attributes is called a sparse array, while an array with a length equal to the numbered attributes is called a dense array.

<code class="language-javascript">var test = function(array) {
  console.log('length:'+ array.length);
  array.forEach(function(element, index, array) {
    console.log(index + ':' + element);
  });
};</code>

Note that when creating a new array, the array literal notation is preferred (defining a new array with empty brackets).

<code class="language-javascript">// 创建一个没有编号条目的数组

var arr = new Array(5);
test(arr);
// length: 5

var arr = [];
arr.length = 5;
test(arr);
// length: 5</code>

Array methods that handle numbered attributes (in this case forEach) will only handle existing attributes. If you loop instead with for or while, the loop also tries to process non-existent properties, and the array identifies non-existent entries as undefined. Your code will then not be able to distinguish the last example above from the first two examples. If you are not sure if you are working on dense arrays, you should always use the array method to process the array.

Change the length of JavaScript array

The following example sees what happens if we set a new length for the array that is smaller than the current length.

<code class="language-javascript">var arr = ['a', 'b', 'c', 'd', 'e'];
test(arr);
// length:5, 0:a, 1:b, 2:c, 3:d, 4:e

var arr = [undefined, undefined, undefined, undefined, undefined];
test(arr);
// length:5, 0:undefined, 1:undefined, 2:undefined, 3:undefined, 4:undefined</code>

Note that when creating an array using the [] notation, each entry consists of a value followed by a comma. If the value is omitted, no attribute is created for that location. The last comma can only be omitted when a value is provided for this property, otherwise the length will be reduced by one.

Removing entries from JavaScript array

JavaScript provides three methods pop, shift and splice to remove entries from an array, thereby reducing the length of the array. In each case, the removed value (or value) is returned by the call.

<code class="language-javascript">var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
test(arr);
// length:6, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

arr.length = 5;
test(arr);
// length:5, 0:a, 1:b, 2:c, 3:d, 4:e

var arr = ['a','b','c','d','e','f',,,];
test(arr);
// length:8, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

arr.length = 7;
test(arr);
// length:7, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f</code>

How to add an entry in an array

We can add new entries to the array by simply specifying where the numbered attribute does not exist yet. We can also use one of the three methods provided by JavaScript (push, unshift and splice) to insert new entries and move old entries if necessary.

<code class="language-javascript">// pop() 从数组中移除最后一个元素
var arr = ['a','b','c','d','e','f'];
var el = arr.pop();
test(arr); // length:5, 0:a, 1:b, 2:c, 3:d, 4:e
console.log(el); // f

// shift() 从数组中移除第一个元素
var arr = ['a','b','c','d','e','f'];
var el = arr.shift();
test(arr); // length:5, 0:b, 1:c, 2:d, 3:e, 4:f
console.log(el); // a

// splice() 可以移除现有元素
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1.splice(0,2); // 从索引0开始移除2个元素
test(arr1); // length:4, 0:c, 1:d, 2:e, 3:f
test(arr2); // length:2, 0:a, 1:b

var arr1 = ['a','b','c','d','e','f',,,'i'];
var arr2 = arr1.splice(6,2); // 从索引6开始移除2个元素
test(arr1); // length:7, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f, 6:i
test(arr2); // length:2</code>

Replace entry in JavaScript array

If we assign a new value to an existing entry, the entry will only get the new value, and the rest of the array will not be affected. Likewise, by combining variants of the splice() method we have studied, we can replace existing entries or fill in blanks in the array.

<code class="language-javascript">var arr = ['a','b','c','d','e','f',,,'i'];
arr[11] = 'l';
test(arr);
// length:12, 0:a, 1:b, 2:c, 3:d, 5:f, 8:i, 11:l

// push() 将一个或多个元素添加到数组的末尾
var arr = ['a','b','c','d','e','f',,,,];
arr.push('j');
test(arr);
// length:10, 0:a, 1:b, 2:c, 3:d, 5:f, 9:j

// unshift() 将一个或多个元素添加到数组的开头
var arr = ['a','b','c','d','e','f',,,,];
arr.unshift('x');
test(arr);
// length:10, 0:x, 1:a, 2:b, 3:c, 4:d, 5:e, 6:f

arr1 = ['a','b','c','d','e','f',,,'i'];
arr2 = arr1.splice(6,0,'g','h'); // 从索引6移除0个元素,并插入'g'、'h'
test(arr1); // length:11, 0:a, 1:b, 2:c, 3:d, 5:f, 6:g, 7:h, 10:i
test(arr2); // length:0</code>

Conclusion

The above example should give you a better understanding of how the length properties of an array work. This can be greater than or equal to the number of entries in the array. If equal, we have a dense array; if greater than, we have a sparse array. The exact role of a particular array method may depend on whether there are properties in the sparse array corresponding to a given position. If we change the length of the array, it removes any numbered attributes in the array whose position is greater than the new length. If the length is equal to the number of numbered attributes, and we increase the length, then we convert dense arrays to sparse arrays. The array method that deletes and adds attributes in an array will move existing entries if necessary and will also preserve and move any gaps between attributes.

JavaScript Array FAQs (FAQs)

How to add elements to arrays in JavaScript?

In JavaScript, you can use the push() method to add elements to an array. This method adds a new item to the end of the array and returns a new length. Here is an example:

<code class="language-javascript">var test = function(array) {
  console.log('length:'+ array.length);
  array.forEach(function(element, index, array) {
    console.log(index + ':' + element);
  });
};</code>

How to remove elements from JavaScript array?

JavaScript provides several ways to remove elements from an array. The pop() method removes the last element from the array and returns the element. The shift() method removes the first element from the array and returns the element. Here are how to use these methods:

<code class="language-javascript">// 创建一个没有编号条目的数组

var arr = new Array(5);
test(arr);
// length: 5

var arr = [];
arr.length = 5;
test(arr);
// length: 5</code>

(The subsequent FAQ content is consistent with the original text, omitted here to avoid duplication)

The above is the detailed content of JavaScript Arrays: How to Create and Manipulate. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn