📜  JavaScript数组

📅  最后修改于: 2020-09-27 04:10:21             🧑  作者: Mango

在本教程中,您将借助示例学习JavaScript数组。

如您所知,变量可以存储单个元素。如果需要一次存储多个元素,则可以使用数组。

数组是可以存储多个元素的对象 。例如,

let myArray = ['hello', 'world', 'welcome'];

创建一个数组

您可以使用两种方法创建数组:

1.使用数组字面量

创建数组的最简单方法是使用数组字面量 [] 。例如,

let array1 = ["eat", "sleep"];

2. 使用new关键字

您还可以使用JavaScript的new关键字创建一个数组。

let array2 = new Array("eat", "sleep");

在以上两个示例中,我们都创建了一个包含两个元素的数组。

注意 :建议使用数组字面量来创建数组。

这里是数组的更多示例:

// empty array
let myList = [ ];
// array containing number values
let numberArray = [ 2, 4, 6, 8];

// array containing string values
let stringArray = [ 'eat', 'work', 'sleep'];

// multiple data types array
let newData = ['work', 'exercise', 1, true];

您还可以在数组内存储数组,函数和其他对象。例如,

let newData = [
    {'task1': 'exercise'},
    [1, 2 ,3],
    function hello() { console.log('hello')}
];

数组的访问元素

您可以使用索引(0,1,2…)访问数组内部的元素。例如,

let myArray = ['h',  'e', 'l', 'l', 'o'];

// first element
console.log(myArray[0]);  // "h"

// second element
console.log(myArray[1]); // "e"
Array indexing in JavaScript
JavaScript中的数组索引

注意 :数组的索引以0开头,而不是1。


将元素添加到数组

您可以使用内置方法push()unshift()将元素添加到数组中。

push()方法在数组的末尾添加一个元素,并返回新数组的长度。例如,

let dailyActivities = ['eat', 'sleep'];

// add an element at the end of the array
dailyActivities.push('exercise');

console.log(dailyActivities); //  ['eat', 'sleep', 'exercise']

unshift()方法将新元素添加到数组的开头,并返回数组的新长度。例如,

let dailyActivities = ['eat', 'sleep'];

//add an element at the end of the array
dailyActivities.unshift('work'); 

console.log(dailyActivities); // ['work', 'eat', 'sleep', 'exercise'']

更改数组的元素

您还可以通过访问索引值来添加元素或更改元素。

let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 2 index
dailyActivities[2] = 'exercise';

console.log(dailyActivities); // ['eat', 'sleep', 'exercise']

假设一个数组有两个元素。如果尝试在索引3(第四个元素)处添加一个元素,则第三个元素将是未定义的。例如,

let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 3 index
dailyActivities[3] = 'exercise';

console.log(dailyActivities); // ["eat", "sleep", undefined, "exercise"]

Basically, if you try to add elements to high indices, the indices in between will have undefined value.

从数组中删除元素

您可以使用pop()方法从数组中删除最后一个元素。 pop()方法还返回返回的值。例如,

let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];

// remove the last element
dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']

// remove the last element from ['work', 'eat', 'sleep']
let removedElement = dailyActivities.pop();

//get removed element
console.log(removedElement); // 'sleep'
console.log(dailyActivities);  // ['work', 'eat']

如果需要删除第一个元素,则可以使用shift()方法。 shift()方法删除第一个元素,并返回删除的元素。例如,

let dailyActivities = ['work', 'eat', 'sleep'];

// remove the first element
dailyActivities.shift();

console.log(dailyActivities); // ['eat', 'sleep']

数组长度

您可以使用length属性找到元素的长度(数组中元素的数量)。例如,

let dailyActivities = [ 'eat', 'sleep'];

// this gives the total number of elements in an array
console.log(dailyActivities.length); // 2

数组方法

在JavaScript中,可以使用多种方法来处理数组,从而可以更轻松地执行有用的计算。

一些常用的JavaScript数组方法是:

Method Description
concat() joins two or more arrays and returns a result
indexOf() searches an element of an array and returns its position
find() returns the first value of an array element that passes a test
findIndex() returns the first index of an array element that passes a test
forEach() calls a function for each element
includes() checks if an array contains a specified element
push() aads a new element to an end of an array and returns the new length of an array
unshift() adds a new element to the beginning of an array and returns the new length of an array
pop() removes the last element of an array and returns the removed element
shift() removes the first element of an array and returns the removed element
sort() sorts the elements alphabetically in strings and in ascending order
slice() selects the part of an array and returns the new array
splice() remove or replace existing elements and/or adding new elements

示例:JavaScript数组方法

let dailyActivities = ['sleep', 'work', 'exercise']
let newRoutine = ['eat'];

// sorting elements in the alphabetical order
dailyActivities.sort();
console.log(dailyActivities); // ['exercise', 'sleep', 'work']

//finding the index position of string
let position = dailyActivities.indexOf('work');
console.log(position); // 2

// slicing the array elements
let newDailyActivities = dailyActivities.slice(1);
console.log(newDailyActivities); // [ 'sleep', 'work']

// concatenating two arrays
let routine = dailyActivities.concat(newRoutine);
console.log(routine); // ["exercise", "sleep", "work", "eat"]

注意 :如果元素不在数组中,则indexOf()给出-1。

访问JavaScript数组方法以了解更多信息。


JavaScript数组的工作

在JavaScript中,数组是一个对象。并且,数组的索引是对象键。

由于数组是对象,因此数组元素通过引用存储。因此,将数组值复制到另一个变量时,复制的数组中的任何更改也将反映在原始数组中。例如,

let arr = ['h', 'e'];
let arr1 = arr;
arr1.push('l');

console.log(arr); // ["h", "e", "l"]
console.log(arr1); // ["h", "e", "l"]

您还可以通过在数组中传递命名键来存储值。例如,

let arr = ['h', 'e'];
arr.name = 'John';

console.log(arr); // ["h", "e"]
console.log(arr.name); // "John"
console.log(arr['name']); // "John"
Array indexing in JavaScript
JavaScript中的数组索引

但是,不建议通过在数组中传递任意名称来存储值。

因此,在JavaScript中,如果值位于有序集合中,则应使用数组。否则,最好将{ }与object一起使用。


推荐文章

  • JavaScript forEach
  • 适用于…的JavaScript
  • JavaScript多维数组