📜  Javascript index,length,push,pop,shift,unshift - Javascript (1)

📅  最后修改于: 2023-12-03 15:31:37.613000             🧑  作者: Mango

Javascript index, length, push, pop, shift, and unshift

JavaScript is a popular programming language used widely on the web. It has a set of built-in functions that make it easy to manipulate arrays. Here are some commonly used array functions in JavaScript.

Index

Arrays in JavaScript are zero-indexed, meaning that the first element is at index 0, the second at index 1, and so on. To access the value of an element in an array, you can use the [] notation with the index of the element you want to access.

For example, to access the second element in an array called myArray, you can use the following code:

const myArray = ['apple', 'banana', 'orange'];
console.log(myArray[1]); // Output: 'banana'
Length

The length property returns the number of elements in an array.

const myArray = ['apple', 'banana', 'orange'];
console.log(myArray.length); // Output: 3
Push

The push method adds one or more elements to the end of an array and returns the new length of the array.

const myArray = ['apple', 'banana', 'orange'];
myArray.push('peach');
console.log(myArray); // Output: ['apple', 'banana', 'orange', 'peach']

You can also push multiple elements at once:

const myArray = ['apple', 'banana', 'orange'];
myArray.push('peach', 'mango');
console.log(myArray); // Output: ['apple', 'banana', 'orange', 'peach', 'mango']
Pop

The pop method removes the last element from an array and returns that element.

const myArray = ['apple', 'banana', 'orange'];
const lastElement = myArray.pop();
console.log(myArray); // Output: ['apple', 'banana']
console.log(lastElement); // Output: 'orange'
Shift

The shift method removes the first element from an array and returns that element.

const myArray = ['apple', 'banana', 'orange'];
const firstElement = myArray.shift();
console.log(myArray); // Output: ['banana', 'orange']
console.log(firstElement); // Output: 'apple'
Unshift

The unshift method adds one or more elements to the beginning of an array and returns the new length of the array.

const myArray = ['apple', 'banana', 'orange'];
myArray.unshift('peach');
console.log(myArray); // Output: ['peach', 'apple', 'banana', 'orange']

You can also unshift multiple elements at once:

const myArray = ['apple', 'banana', 'orange'];
myArray.unshift('peach', 'mango');
console.log(myArray); // Output: ['peach', 'mango', 'apple', 'banana', 'orange']

These are just a few of the many built-in array functions in JavaScript that can be used to manipulate arrays. Knowing these functions can make it much easier to work with arrays in JavaScript.