Home >Web Front-end >JS Tutorial >Explanation on Arrays and Arrays method
Detailed explanation and common methods of JavaScript arrays:
What is an array?
In JavaScript, an array is a special object used to store a series of values (elements) under a variable name. The values can be of different data types (numbers, strings, booleans, objects, or even other arrays).
Main features:
Create array:
<code class="language-javascript"> const myArray = [1, "hello", true, null]; </code>
<code class="language-javascript"> const anotherArray = new Array(5); // 创建一个包含5个空槽的数组 const yetAnotherArray = new Array(1, 2, 3); </code>
Access array elements:
Use square bracket notation and indexing:
<code class="language-javascript"> const fruits = ["apple", "banana", "orange"]; console.log(fruits[0]); // 输出: "apple" (第一个元素) console.log(fruits[2]); // 输出: "orange" (第三个元素)</code>
Modify array elements:
Assign the new value to the desired index:
<code class="language-javascript"> fruits[1] = "grape"; console.log(fruits); // 输出: ["apple", "grape", "orange"]</code>
Commonly used array methods:
<code class="language-javascript"> fruits.push("mango"); </code>
<code class="language-javascript"> const removedFruit = fruits.pop(); </code>
<code class="language-javascript"> fruits.unshift("kiwi"); </code>
<code class="language-javascript"> const firstFruit = fruits.shift(); </code>
<code class="language-javascript"> const citrusFruits = fruits.slice(1, 3); // 从索引1到2(不包括2)的元素</code>
<code class="language-javascript"> fruits.splice(1, 0, "pear"); // 在索引1处插入"pear" fruits.splice(2, 1); // 从索引2处删除1个元素</code>
<code class="language-javascript"> const combinedFruits = fruits.concat(["pineapple", "strawberry"]); </code>
<code class="language-javascript"> const fruitString = fruits.join(", "); </code>
<code class="language-javascript"> const index = fruits.indexOf("apple"); </code>
<code class="language-javascript"> const hasBanana = fruits.includes("banana"); </code>
<code class="language-javascript"> fruits.forEach(fruit => console.log(fruit)); </code>
<code class="language-javascript"> const fruitLengths = fruits.map(fruit => fruit.length); </code>
<code class="language-javascript"> const longFruits = fruits.filter(fruit => fruit.length > 5); </code>
This is a basic overview of JavaScript arrays and their methods. There are many other methods available, each with its own specific purpose. Hope this helps!
The above is the detailed content of Explanation on Arrays and Arrays method. For more information, please follow other related articles on the PHP Chinese website!