天天看點

JavaScript标準對象:數組

Surely you've heard that, in JavaScript, everything is an object. Strings, numbers, functions, arrays, and, well, objects are considered objects.

您肯定已經聽說過,在JavaScript中,一切都是對象。 字元串,數字,函數,數組以及對象都被視為對象。

In this tutorial we'll take a deep dive into the Array "global" or "standard built-in" object, along with the methods associated with it.

在本教程中,我們将深入研究Array的 “全局”或“标準内置”對象以及與之關聯的方法。

什麼是數組? (What's an array?)

In JavaScript, an array is a list-like object that stores comma separated values. These values can be anything – strings, numbers, objects, or even functions.

在JavaScript中,數組是一個清單形式的對象,用于存儲逗号分隔的值。 這些值可以是任何值-字元串,數字,對象甚至函數。

Arrays start with an opening bracket (

[

) and end with a closing bracket (

]

), use numbers as element indexes.

數組以方括号(

[

)開始,以方括号(

]

)結尾,并使用數字作為元素索引。

如何建立數組: (How to create an array:)

const shoppingList = ['Bread', 'Cheese', 'Apples'];
           

使用括号表示法通路數組中的值 (Access a value in an array with bracket notation)

const shoppingList = ['Bread', 'Cheese', 'Apples'];

console.log(shoppingList[1])
// Cheese
           

The array standard object has a number of useful methods, some of which are listed below.

數組标準對象有許多有用的方法,下面列出了其中的一些方法。

Array.prototype.isArray() (Array.prototype.isArray())

The

Array.isArray()

method returns

true

if an object is an array,

false

if it is not.

如果對象是數組,則

Array.isArray()

方法傳回

true

否則傳回

false

句法 (Syntax)

Array.isArray(obj)
           

參量 (Parameters)

obj The object to be checked.

obj要檢查的對象。

.isArray()的示例 (Examples of .isArray())

// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype); 

// all following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });
           

Array.prototype.length (Array.prototype.length)

length

is a property of arrays in JavaScript that returns or sets the number of elements in a given array.

length

是JavaScript中數組的屬性,它傳回或設定給定數組中的元素數。

The

length

property of an array can be returned like so.

數組的

length

屬性可以這樣傳回。

let desserts = ["Cake", "Pie", "Brownies"];
console.log(desserts.length); // 3
           

The assignment operator, in conjunction with the

length

property, can be used to set then number of elements in an array like so.

指派運算符與

length

屬性一起可用于像這樣設定數組中元素的數量。

let cars = ["Saab", "BMW", "Volvo"];
cars.length = 2;
console.log(cars.length); // 2
           

Array.prototype.push (Array.prototype.push)

The

push()

method is used to add one or more new elements to the end of an array. It also returns the new length of the array. If no arguments are provided, it will simply return the current length of the array.

push()

方法用于将一個或多個新元素添加到數組的末尾。 它還傳回數組的新長度。 如果未提供任何參數,它将僅傳回數組的目前長度。

句法 (Syntax)

arr.push([element1[, ...[, elementN]]])
           

參量 (Parameters)

  • elementN The elements to add to the end of the array.

    elementN要添加到數組末尾的元素。

傳回值 (Return value)

The new length of the array on which the method was called.

調用該方法的數組的新長度。

例: (Example:)

let myStarkFamily = ['John', 'Robb', 'Sansa', 'Bran'];
           

Suppose you have an array of the children of House Stark from Game of Thrones. However, one of the members, Arya, is missing. Knowing the code above, you could add her by assigning

'Arya'

to the array at the index after the last index like so:

假設您有一個由《權力的遊戲》中的史塔克家族的孩子組成的陣列。 但是,成員之一Arya失蹤了。 了解了上面的代碼,您可以通過在最後一個索引之後的索引處将

'Arya'

配置設定給數組來添加她,如下所示:

myStarkFamily[4] = 'Arya';
           

The problem with this solution is that it can’t handle general cases. If you didn’t know beforehand what the length of the array is, you can’t add new elements this way. This is what

push()

is for. We don’t need to know how long the array is. We just add our element to the end of the array.

該解決方案的問題在于它無法處理一般情況。 如果您事先不知道數組的長度,則無法以這種方式添加新元素。 這就是

push()

的作用。 我們不需要知道數組有多長。 我們隻是将元素添加到數組的末尾。

myStarkFamily.push('Arya');
console.log(myStarkFamily);  // ['John', 'Robb', 'Sansa', 'Bran', 'Arya']

let newLength = myStarkFamily.push('Rickon');  // oops! forgot Rickon
console.log(newLength);  // 6
console.log(myStarkFamily);  // ['John', 'Robb', 'Sansa', 'Bran', 'Arya', 'Rickon']
           

Array.prototype.reverse (Array.prototype.reverse)

The JavaScript array method

.reverse()

will reverse the order of the elements within the array.

JavaScript數組方法

.reverse()

将反轉數組中元素的順序。

Syntax

句法

let array = [1, 2, 3, 4, 5];
  array.reverse();
           

描述 (Description)

.reverse()

reverses the index of the elements of an array.

.reverse()

反轉數組元素的索引。

例子 (Examples)

Use

.reverse()

to reverse the elements of an array

使用

.reverse()

反轉數組的元素

let array = [1, 2, 3, 4, 5];
  console.log(array);
  // Console will output 1, 2, 3, 4, 5

  array.reverse();

  console.log(array);
  /* Console will output 5, 4, 3, 2, 1 and
  the variable array now contains the set [5, 4, 3, 2, 1] */
           

Array.prototype.indexOf (Array.prototype.indexOf)

The

indexOf()

method returns the first index at which a given element can be found in the array. If the element is not present, it returns -1.

indexOf()

方法傳回可以在數組中找到給定元素的第一個索引。 如果該元素不存在,則傳回-1。

The

indexOf()

takes an element you want to search for as a parameter, iterates through the elements in an array, and returns the first index where the element can be found. If the element is not in the array,

indexOf

returns -1.

indexOf()

将要搜尋的元素作為參數,周遊數組中的元素,然後傳回可以找到該元素的第一個索引。 如果元素不在數組中,則

indexOf

傳回-1。

Syntax

句法

arr.indexOf(searchElement[, fromIndex])
           

Parameters

參量

  • searchElement: The element you're searching for.

    searchElement :要搜尋的元素。

  • fromIndex (Optional): The index at which you want to start the search at. If the

    fromIndex

    is greater than or equal to the array’s length, the array is not searched and the method returns -1. If the fromIndex is a negative number, it considered an offset from the end of the array (the array is still searched forwards from there). The default value is 0, which means the entire array is searched.

    fromIndex (可選):您要從其開始搜尋的索引。 如果

    fromIndex

    大于或等于數組的長度,則不搜尋數組,該方法傳回-1。 如果fromIndex是負數,則它被認為是距數組末尾的偏移量(仍從該數組開始向前搜尋數組)。 預設值為0,表示搜尋整個數組。
  • The array index you want to start searching form. The default value is 0, meaning the search starts from the first index of the array. If

    fromIndex

    is greater than or equal to the array's length, then the method doesn't search the array and returns -1.

    您要開始搜尋表單的數組索引。 預設值為0,表示搜尋從數組的第一個索引開始。 如果

    fromIndex

    大于或等于數組的長度,則該方法不搜尋數組并傳回-1。

例子 (Examples)

var array = [1, 2, 4, 1, 7]

array.indexOf(1); // 0
array.indexOf(7); // 4
array.indexOf(6); // -1
array.indexOf('1'); // -1
array.indexOf('hello'); // -1
array.indexOf(1, 2); // 3
array.indexOf(1, -3); // 3
           

Array.prototype.findIndex (Array.prototype.findIndex)

The

findIndex()

method goes through an array and tests every element against the testing function that's passed as a parameter. It returns the index of the first element of the array that returns true against the testing functions. If no elements return true,

findIndex()

returns -1.

findIndex()

方法周遊數組,并針對作為參數傳遞的測試函數對每個元素進行測試。 它傳回數組的第一個元素的索引,該元素針對測試函數傳回true。 如果沒有元素傳回true,則

findIndex()

傳回-1。

Note that

findIndex()

does not mutate the array it's called on.

請注意,

findIndex()

不會使調用它的數組發生突變。

Syntax

句法

arr.findIndex(callback(element, index, array), [thisArg])
           
參量 (Parameters)

callback

: Function to execute on each value in the array, which takes three arguments:

callback

:對數組中的每個值執行的函數,該函數帶有三個參數:

  • element

    : The current element being processed in the array.

    element

    :數組中正在處理的目前元素。
  • index

    : The index of the current element being processed in the array.

    index

    :數組中正在處理的目前元素的索引。
  • array

    : The array findIndex() was called upon.

    array

    :數組findIndex()被調用。

thisArg

(Optional): An object to use as

this

when executing the callback function.

thisArg

(可選):執行回調函數時用作

this

對象的對象。

例子 (Examples)

This example will find the corresponding item in the array and return the index from it.

本示例将在數組中找到相應的項目并從中傳回索引。

let items = [
    {name: 'books', quantity: 2},
    {name: 'movies', quantity: 1},
    {name: 'games', quantity: 5}
];

function findMovies(item) { 
    return item.name === 'movies';
}

console.log(items.findIndex(findMovies));

// Index of 2nd element in the Array is returned,
// so this will result in '1'
           

The following example shows the output of each optional parameter to the callback function. This will return

-1

because none of the items will return true from the callback function.

以下示例顯示了每個可選參數到回調函數的輸出。 這将傳回

-1

因為所有項都不會從回調函數傳回true。

function showInfo(element, index, array) {
  console.log('element = ' + element + ', index = ' + index + ', array = ' + array);
  return false;
}

console.log('return = ' + [4, 6, 8, 12].findIndex(showInfo));

// Output
//  element = 4, index = 0, array = 4,6,8,12
//  element = 6, index = 1, array = 4,6,8,12
//  element = 8, index = 2, array = 4,6,8,12
//  element = 12, index = 3, array = 4,6,8,12
//  return = -1
           

Array.prototype.find (Array.prototype.find)

The

find()

method goes through an array and tests every element against the testing function that's passed as a parameter. It returns the value of the first element of the array that returns true against the testing functions. If no elements return true,

find()

returns

undefined

.

find()

方法周遊數組,并針對作為參數傳遞的測試函數對每個元素進行測試。 它傳回數組的第一個元素的值,該元素對測試函數傳回true。 如果沒有元素傳回true,則

find()

傳回

undefined

Note that

find()

does not mutate the array it's called on.

請注意,

find()

不會使它調用的數組發生變化。

句法 (Syntax)

arr.find(callback(element, index, array), [thisArg])
           
參量 (Parameters)

callback

: Function to execute on each value in the array. It takes three arguments:

callback

:對數組中的每個值執行的函數。 它包含三個參數:

  • element

    : The current element being processed in the array.

    element

    :數組中正在處理的目前元素。
  • index

    : The index of the current element being processed in the array.

    index

    :數組中正在處理的目前元素的索引。
  • array

    : The array find was called upon.

    array

    :調用了數組查找。

thisArg

(Optional): An object to use as

this

when executing the callback function.

thisArg

(可選):執行回調函數時用作

this

對象的對象。

例子 (Examples)

This example will find the corresponding item in the array and return the object from it.

本示例将在數組中找到相應的項目,并從中傳回對象。

let items = [
    {name: 'books', quantity: 2},
    {name: 'movies', quantity: 1},
    {name: 'games', quantity: 5}
];

function findMovies(item) { 
    return item.name === 'movies';
}

console.log(items.find(findMovies));

// Output
//  { name: 'movies', quantity: 1 }
           

The following example shows the output of each optional parameter to the callback function. This will return

undefined

because none of the items will return true from the callback function.

以下示例顯示了每個可選參數到回調函數的輸出。 這将傳回

undefined

因為沒有任何一項将從回調函數傳回true。

function showInfo(element, index, array) {
  console.log('element = ' + element + ', index = ' + index + ', array = ' + array);
  return false;
}

console.log('return = ' + [4, 6, 8, 12].find(showInfo));

// Output
//  element = 4, index = 0, array = 4,6,8,12
//  element = 6, index = 1, array = 4,6,8,12
//  element = 8, index = 2, array = 4,6,8,12
//  element = 12, index = 3, array = 4,6,8,12
//  return = undefined
           

Array.prototype.join (Array.prototype.join)

The JavaScript array method

.join()

will combine all elements of an array into a single string.

JavaScript數組方法

.join()

将數組的所有元素組合為一個字元串。

Syntax

句法

const array = ["Lorem", "Ipsum", "Dolor", "Sit"];
  const str = array.join([separator]);
           

參量 (Parameters)

separator Optional. Specifies the string to use to separate each element of the original array. If the separator is not a string, it will be converted to a string. If separator parameter is not provided, array elements are separated with a comma by default. If separator is an empty string

""

, all array elements are joined without a separator character between them.

分隔符可選。 指定用于分隔原始數組的每個元素的字元串。 如果分隔符不是字元串,則會将其轉換為字元串。 如果未提供分隔符參數,則預設情況下,數組元素用逗号分隔。 如果分隔符為空字元串

""

,則所有數組元素之間都将連接配接,而沒有分隔符。

描述 (Description)

.join()

joins all elements of an array into a single string. If any of the array elements are

undefined

or

null

, that element is converted to the empty string

""

.

.join()

将數組的所有元素連接配接到單個字元串中。 如果任何數組元素

undefined

或為

null

,則該元素将轉換為空字元串

""

例子 (Examples)

Using

.join()

four different ways

四種不同方式使用

.join()

const array = ["Lorem", "Ipsum", "Dolor" ,"Sit"];

const join1 = array.join();           /* assigns "Lorem,Ipsum,Dolor,Sit" to join1 variable
                                     (because no separator was provided .join()
                                     defaulted to using a comma) */
const join2 = array.join(", ");       // assigns "Lorem, Ipsum, Dolor, Sit" to join2 variable
const join3 = array.join(" + ");      // assigns "Lorem + Ipsum + Dolor + Sit" to join3 variable
const join4 = array.join("");         // assigns "LoremIpsumDolorSit" to join4 variable
           

Array.prototype.concat (Array.prototype.concat)

The

.concat()

method returns a new array consisting of the elements of the array on which you call it, followed by the elements of the arguments in the order they are passed.

.concat()

方法傳回一個新數組,該數組由您在其上調用的數組的元素組成,然後按傳遞順序依次傳遞參數的元素。

You can pass multiple arguments to the

.concat()

method. The arguments can be arrays, or data types like booleans, strings, and numbers.

您可以将多個參數傳遞給

.concat()

方法。 參數可以是數組,也可以是資料類型,例如布爾值,字元串和數字。

句法 (Syntax)

const newArray = array.concat(value1, value2, value3...);
           

例子 (Examples)

連接配接兩個數組 (Concatenating two arrays)

const cold = ['Blue', 'Green', 'Purple'];
const warm = ['Red', 'Orange', 'Yellow'];

const result = cold.concat(warm);

console.log(result);
// results in ['Blue', 'Green', 'Purple', 'Red', 'Orange', 'Yellow'];
           

将值連接配接到數組 (Concatenating value to an array)

const odd = [1, 3, 5, 7, 9];
const even = [0, 2, 4, 6, 8];

const oddAndEvenAndTen = odd.concat(even, 10);

console.log(oddAndEvenAndTen);
// results in [1, 3, 5, 7, 9, 0, 2, 4, 6, 8, 10];
           

Array.prototype.slice (Array.prototype.slice)

The JavaScript array method

.slice()

will return a new array object which will be a segment (a slice) of the original array. The original array is not modified.

JavaScript數組方法

.slice()

将傳回一個新的數組對象,該對象将是原始數組的一個片段(一個切片)。 原始數組未修改。

Syntax

句法

array.slice()
  arr.slice(startIndex)
  arr.slice(startIndex, endIndex)
           

參量 (Parameters)

  • startIndex The zero-based index where the slice should begin. If the value is omitted, it will start at 0.

    startIndex切片應從零開始的索引。 如果省略該值,則将從0開始。

  • endIndex The slice will end before this zero-based index. A negative index is used to offset from the end of the array. If the value is omitted, the segment will slice to the end of the array.

    endIndex切片将在此從零開始的索引之前結束。 負索引用于從數組末尾偏移。 如果省略該值,則該段将切片到數組的末尾。

例子 (Examples)

const array = ['books', 'games', 'cup', 'sandwich', 'bag', 'phone', 'cactus']
  
  const everything = array.slice()
  // everything = ['books', 'games', 'cup', 'sandwich', 'bag', 'phone', 'cactus']
  
  const kitchen = array.slice(2, 4)
  // kitchen = ['cup', 'sandwich']
  
  const random = array.slice(4)
  // random = ['bag', 'phone', 'cactus']
  
  const noPlants = array.slice(0, -1)
  // noPlats = ['books', 'games', 'cup', 'sandwich', 'bag', 'phone']
  
  // array will still equal ['books', 'games', 'cup', 'sandwich', 'bag', 'phone', 'cactus']
           

Array.prototype.splice (Array.prototype.splice)

The splice method is similar to Array.prototype.slice, but unlike

slice()

it mutates the array it is called on. It also differs in that it can be used to add values to an array as well as remove them.

splice方法類似于Array.prototype.slice ,但是與

slice()

不同,它使被調用的數組發生突變。 它的不同之處還在于,它可用于将值添加到數組以及删除它們。

參量 (Parameters)

splice()

can take one or more parameters detailed below.

splice()

可以采用下面詳述的一個或多個參數。

拼接(開始) (splice(start))

If only one parameter is included, then

splice(start)

will remove all array elements from

start

to the end of the array.

如果僅包含一個參數,則

splice(start)

将删除從數組的

start

到結尾的所有數組元素。

let exampleArray = ['first', 'second', 'third', 'fourth'];
exampleArray.splice(2);
// exampleArray is now ['first', 'second'];
           

If

start

is negative, it will count backwards from the end of the array.

如果

start

為負,它将從數組末尾

start

倒數。

let exampleArray = ['first', 'second', 'third', 'fourth'];
exampleArray.splice(-1);
// exampleArray is now ['first', 'second', 'third'];
           

拼接(開始,删除計數) (splice(start, deleteCount))

If a second parameter is included, then

splice(start, deleteCount)

will remove

deleteCount

elements from the array, beginning with

start

.

如果包含第二個參數,則

splice(start, deleteCount)

将以

start

開頭從數組中删除

deleteCount

元素。

let exampleArray = ['first', 'second', 'third', 'fourth'];
exampleArray.splice(1, 2);
// exampleArray is now ['first', 'fourth'];
           

拼接(start,deleteCount,newElement1,newElement2,…) (splice(start, deleteCount, newElement1, newElement2, …))

If more than two parameters are included, the additional parameters will be new elements that are added to the array. The location of these added elements will be begin at

start

.

如果包含兩個以上參數,則其他參數将是添加到數組的新元素。 這些添加的元素的位置将從

start

Elements can be added without removing any elements by passing

as the second parameter.

通過将

作為第二個參數傳遞,可以添加元素而不删除任何元素。

let exampleArray = ['first', 'second', 'third', 'fourth'];
exampleArray.splice(1, 0, 'new 1', 'new 2');
// exampleArray is now ['first', 'new 1', 'new 2', 'second', 'third', 'fourth']
           

Elements can also be replaced.

元素也可以替換。

let exampleArray = ['first', 'second', 'third', 'fourth'];
exampleArray.splice(1, 2, 'new second', 'new third');
// exampleArray is now ['first', 'new second', 'new third', 'fourth']
           

傳回值 (Return value)

In addition to changing the array that it is called on,

splice()

also returns an array containing the removed values. This is a way of cutting an array into two different arrays.

除了更改調用它的數組之外,

splice()

還傳回一個包含已删除值的數組。 這是将一個數組切成兩個不同數組的方法。

let exampleArray = ['first', 'second', 'third', 'fourth'];
let newArray = exampleArray.splice(1, 2);
// exampleArray is now ['first', 'fourth']
// newArray is ['second', 'third']
           

Array.prototype.filter (Array.prototype.filter)

The filter method takes an array as an input. It takes each element in the array and it applies a conditional statement against it. If this conditional returns true, the element gets “pushed” to the output array.

filter方法将數組作為輸入。 它接受數組中的每個元素,并對其應用條件語句。 如果此條件傳回true,則該元素被“推送”到輸出數組。

Once each element in the input array is “filtered” as such, it outputs a new array containing each element that returned true.

這樣就對輸入數組中的每個元素進行了“過濾”後,它将輸出一個包含每個傳回true的元素的新數組。

In this example below, there is an array that has multiple objects within it. Normally, to iterate through this array, you might use a for loop.

在下面的示例中,其中有一個包含多個對象的數組。 通常,要周遊此數組,可以使用for循環。

In this case, we want to get all the students whose grades are greater than or equal to 90.

在這種情況下,我們希望獲得所有成績大于或等于90的學生。

const students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
];
//Define an array to push student objects to.
let studentsGrades = []
for (var i = 0; i < students.length; i++) {
  //Check if grade is greater than 90
  if (students[i].grade >= 90) {
    //Add a student to the studentsGrades array.
    studentsGrades.push(students[i])
  }
}

console.log(studentsGrades); // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
           

This for loop works, but it is pretty lengthy. It can also become tedious to write for loops over and over again for many arrays that you need to iterate through.

這個for循環有效,但是很長。 一遍又一遍地為許多需要疊代的數組編寫循環也可能變得很麻煩。

This is a great use case for filter!

這是過濾器的絕佳用例!

Here is the same example using filter:

這是使用過濾器的相同示例:

const students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
];

const studentGrades = students.filter(function (student) {
  //This tests if student.grade is greater than or equal to 90. It returns the "student" object if this conditional is met.
  return student.grade >= 90;
});

console.log(studentGrades); // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
           

The filter method is much faster to write and cleaner to read while still accomplishing the same thing. Using ES6 syntax we can even replicate the 6-line for-loop with filter:

filter方法的編寫速度更快,閱讀方法更清晰,同時還能完成相同的工作。 使用ES6文法,我們甚至可以使用filter複制6行for循環:

const students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
];

const studentGrades = students.filter(student => student.grade >= 90);
console.log(studentGrades); // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
           

Filter is very useful and a great choice over for loops to filter arrays against conditional statements.

篩選器非常有用,并且是選擇循環以根據條件語句篩選數組的絕佳選擇。

Array.prototype.forEach (Array.prototype.forEach)

The

.forEach()

array method is used to iterate through each item in an array. The method is called on the array object and is passed a function that is called on each item in the array.

.forEach()

數組方法用于周遊數組中的每個項目。 該方法在數組對象上調用,并傳遞給在數組中每個項目上調用的函數。

let arr = [1, 2, 3, 4, 5];

arr.forEach(number => console.log(number * 2));

// 2
// 4
// 6
// 8
// 10
           

The callback function can also take a second parameter of an index in case you need to reference the index of the current item in the array.

如果您需要引用數組中目前項目的索引,則回調函數還可以使用索引的第二個參數。

let arr = [1, 2, 3, 4, 5];

arr.forEach((number, i) => console.log(`${number} is at index ${i}`));

// '1 is at index 0'
// '2 is at index 1'
// '3 is at index 2'
// '4 is at index 3'
// '5 is at index 4'
           

Array.prototype.reduce (Array.prototype.reduce)

The

reduce()

method reduces an array of values down to just one value. It's been called the Swiss Army knife, or multi-tool, of array transformation methods. Others, such as

map()

and

filter()

, provide more specific transformations, whereas

reduce()

can be used to transform arrays into any output you desire.

reduce()

方法将值數組減少為一個值。 它被稱為數組轉換方法的瑞士軍刀或多功能工具。 其他函數

map()

例如

map()

filter()

提供了更具體的轉換,而

reduce()

可用于将數組轉換為所需的任何輸出。

句法 (Syntax)

arr.reduce(callback[, initialValue])
           

The

callback

argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

callback

參數是一個函數,将為數組中的每個項目調用一次。 該函數有四個參數,但通常僅使用前兩個參數。

  • accumulator - the returned value of the previous iteration

    累加器 -上一次疊代的傳回值

  • currentValue - the current item in the array

    currentValue-數組中的目前項目

  • index - the index of the current item

    index-目前項目的索引

  • array - the original array on which reduce was called

    array-在其上調用reduce的原始數組

  • The

    initialValue

    argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function (see Example 2 below).

    initialValue

    參數是可選的。 如果提供的話,它将在第一次調用回調函數時用作初始累加器值(請參見下面的示例2)。

例子1 (Example 1)

Transform an array of integers into the sum of all integers in the array.

将整數數組轉換為數組中所有整數的和。

const numbers = [1,2,3]; 
const sum = numbers.reduce(function(total, current){
    return total + current;
});
console.log(sum);
           

This will output

6

to the console.

這會将

6

輸出到控制台。

例子2 (Example 2)

Transform an array of strings into a single object that shows how many times each string appears in the array. Notice this call to reduce passes an empty object

{}

as the

initialValue

parameter. This will be used as the initial value of the accumulator (the first argument) passed to the callback function.

将字元串數組轉換為單個對象,該對象顯示每個字元串出現在數組中的次數。 注意,該reduce調用将空對象

{}

作為

initialValue

參數傳遞。 這将用作傳遞給回調函數的累加器(第一個參數)的初始值。

const pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

const petCounts = pets.reduce(function(obj, pet){
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
}, {});

console.log(petCounts);
           

Output:

輸出:

{ 
    dog: 2, 
    chicken: 3, 
    cat: 1, 
    rabbit: 1 
 }
           

Array.prototype.sort (Array.prototype.sort)

This method sorts the elements of an array in place and returns the array.

此方法對數組中的元素進行适當排序,然後傳回數組。

The

sort()

method follows the ASCII order!

sort()

方法遵循ASCII順序 !

let myArray = ['#', '!'];
let sortedArray = myArray.sort();   // ['!', '#'] because in the ASCII table "!" is before "#"

myArray = ['a', 'c', 'b'];
console.log(myArray.sort()); // ['a', 'b', 'c']
console.log(myArray) // ['a', 'b', 'c']

myArray = ['b', 'a', 'aa'];
console.log(myArray.sort());   // ['a', 'aa', 'b']

myArray = [1, 2, 13, 23];
console.log(myArray.sort());   // [1, 13, 2, 23] numbers are treated like strings!
           

進階用法 (Advanced usage)

The

sort()

method can also accept a parameter:

array.sort(compareFunction)

sort()

方法還可以接受以下參數:

array.sort(compareFunction)

例如 (For example)

function compare(a, b){
  if (a < b){return -1;}
  if (a > b){return 1;}
  if (a === b){return 0;}
}

let myArray = [1, 2, 23, 13];
console.log(myArray.sort()); // [ 1, 13, 2, 23 ]
console.log(myArray.sort(compare));   // [ 1, 2, 13, 23 ]

myArray = [3, 4, 1, 2];
sortedArray = myArray.sort(function(a, b){.....});   // it depends from the compareFunction
           

Array.prototype.some() (Array.prototype.some())

The JavaScript array method

.some()

will take a callback function to test each element in the array; once the callback returns

true

then

.some()

will return true immediately.

JavaScript數組方法

.some()

将使用回調函數來測試數組中的每個元素; 一旦回調傳回

true

.some()

将立即傳回true。

Syntax

句法

var arr = [1, 2, 3, 4];
  arr.some(callback[, thisArg]);
           

回調功能 (Callback Function)

Syntax

句法

var isEven = function isEven(currentElement, index, array) {
      if(currentElement % 2 === 0) {
          return true;
      } else {
          return false;
      }
  }
           

See wiki on Arithmetic Operators to see the remainder operator

%

請參閱算術運算符上的Wiki以檢視餘數運算符

%

Has 3 arguments

有3個論點

currentElement

currentElement

  • this is a variable that represents the element that is being passed to the callback.

    這是一個變量,表示要傳遞給回調的元素。

index

指數

  • this is the index value of the current element starting at 0

    這是目前元素的索引值,從0開始

array

數組

  • the array that

    .some()

    was call on.

    .some()

    被調用的數組。

The callback function should implement a test case.

回調函數應實作一個測試用例。

thisArg (thisArg)

Is an optional parameter and more info can be found at the [MDN

是可選參數,更多資訊可以在[MDN

描述 (Description)

.some()

will run the callback function for each element in the array. Once the callback returns true,

.some()

will return

true

. If the callback returns a falsy value for every element in the array then

.some()

returns false.

.some()

将為數組中的每個元素運作回調函數。 一旦回調傳回true,

.some()

将傳回

true

。 如果回調為數組中的每個元素傳回一個假值 ,則

.some()

傳回false。

.some()

will not change/mutate the array that called it.

.some()

不會更改/更改調用它的數組。

例子 (Examples)

Passing a function to

.some()

将函數傳遞給

.some()

const isEven = function isEven(currentElement, index, array) {
  if(currentElement % 2 === 0) {
      return true;
  } else {
      return false;
  }
}

const arr1 = [1, 2, 3, 4, 5, 6];
arr1.some(isEven);  // returns true
const arr2 = [1, 3, 5, 7];
arr2.some(isEven);  // returns false
           

Anonymous function

匿名功能

const arr3 = ['Free', 'Code', 'Camp', 'The Amazing'];
arr3.some(function(curr, index, arr) {
  if (curr === 'The Amazing') {
      return true;
  } 
}); // returns true

const arr4 = [1, 2, 14, 5, 17, 9];
arr4.some(function(curr, index, arr) {
  return curr > 20;
  });  // returns false

// ES6 arrows functions
arr4.some((curr) => curr >= 14)  // returns true
           

Array.prototype.Every (Array.prototype.every)

The

every()

method tests every whether every element in the array passes the provided test.

every()

方法會測試數組中的每個元素是否通過提供的測試。

Syntax

句法

arr.every(callback[, thisArg])
           

參量 (Parameters)

  1. The callback takes up to three arguments:

    回調最多包含三個參數:

  • currentValue (required) – The current element in the array.

    currentValue (必填)–數組中的目前元素。

  • index (optional) – The index or the current element in the array.

    index (可選)–數組中的索引或目前元素。

  • array (optional) – The array the

    every

    method was called on.

    array (可選)–調用了

    every

    方法的數組。

2.  thisArg is optional. It's the value used as

this

in the callback.

2. thisArg是可選的。 這是用作值

this

回調。

描述 (Description)

The

every

method calls the

callback

function one time for each array element, in ascending index order, until the

callback

function returns false. If an element that causes

callback

to return false is found, the every method immediately returns

false

. Otherwise, the every method returns

true

.

every

方法調用

callback

為每個陣列元件的功能一時刻在升序索引順序,直到該

callback

函數傳回假。 如果找到導緻

callback

傳回false的元素,則every方法立即傳回

false

。 否則,every方法将傳回

true

The callback function is not called for missing elements of the array.

對于缺少數組元素的元素,不會調用回調函數。

In addition to array objects, the every method can be used by any object that has a length property and that has numerically indexed property names.

every

does not mutate the array on which it is called.

除數組對象外,任何具有length屬性并且具有數字索引屬性名稱的對象都可以使用every方法。

every

不會改變其調用的數組。

例子 (Examples)

function isBigEnough(element, index, array) {
    return element >= 10;
  }
  [12, 5, 8, 130, 44].every(isBigEnough);   // false
  [12, 54, 18, 130, 44].every(isBigEnough); // true

  // Define the callback function.
  function CheckIfEven(value, index, ar) {
      document.write(value + " ");

      if (value % 2 == 0)
          return true;
      else
          return false;
  }

  // Create an array.
  var numbers = [2, 4, 5, 6, 8];

  // Check whether the callback function returns true for all of the
  // array values.
  if (numbers.every(CheckIfEven))
      document.write("All are even.");
  else
      document.write("Some are not even.");

  // Output:
  // 2 4 5 Some are not even.
           

Array.prototype.map (Array.prototype.map)

The

.map()

method loops through the given array and executes the provided function on each element. It returns a new array which contains the results of the function call on each element.

.map()

方法循環周遊給定的數組,并在每個元素上執行提供的功能。 它傳回一個新數組,其中包含對每個元素的函數調用的結果。

例子 (Examples)

ES5

ES5

var arr = [1, 2, 3, 4];
var newArray = arr.map(function(element) { return element * 2});
console.log(newArray); // [2, 4, 6, 8]
           

ES6

ES6

const arr = [1, 2, 3, 4];
const newArray = arr.map(element => element * 2);
console.log(newArray);
//[2, 4, 6, 8]
           

Array.prototype.includes (Array.prototype.includes)

The

includes()

method determines whether an array includes a value. It returns true or false.

includes()

方法确定數組是否包含值。 它傳回true或false。

It takes two arguments:

它有兩個參數:

  1. searchValue

    - The element to search for in the array.

    searchValue

    要在數組中搜尋的元素。
  2. fromIndex

    - The position in the array to start searching for the proivded

    searchValue

    . If a negative value is supplied it starts from the array’s length minus the negative value.

    fromIndex

    數組中開始搜尋提供的

    searchValue

    。 如果提供負值,則從數組長度減去負值開始。

例 (Example)

const a = [1, 2, 3];
a.includes(2); // true 
a.includes(4); // false
           

Array.prototype.toLocaleString (Array.prototype.toLocaleString)

The

toLocaleString()

method returns a string representing the elements of an array. All the elements are converted to Strings using their toLocaleString methods. The result of calling this function is intended to be locale-specific.

toLocaleString()

方法傳回一個表示數組元素的字元串。 所有元素都使用其toLocaleString方法轉換為String。 調用此函數的結果旨在特定于語言環境。

句法: (Syntax:)
arr.toLocaleString();
           
參量 (Parameters)
  • locales

    (Optional) - argument holding either a string or an array of language tags BCP 47 language tag.

    locales

    (可選)-參數,包含字元串或語言标簽數組BCP 47語言标簽 。
  • options

    (Optional) - object with configuration properties

    options

    (可選)-具有配置屬性的對象
傳回值 (Return value)

A string representing the elements of the array separated by a locale-specific String (such as a comma “,”)

一個字元串,代表由區域設定特定的字元串分隔的數組元素(例如,逗号“,”)

例子 (Examples)

const number = 12345;
const date = new Date();
const myArray = [number, date, 'foo'];
const myString = myArray.toLocaleString(); 

console.log(myString); 
// OUTPUT '12345,10/25/2017, 4:20:02 PM,foo'
           

Different outputs could be displayed based on the language and region identifier (the locale).

可以基于語言和區域辨別符(區域設定)顯示不同的輸出。

const number = 54321;
const date = new Date();
const myArray = [number, date, 'foo'];
const myJPString = myArray.toLocaleString('ja-JP');

console.log(myJPString);
// OUTPUT '54321,10/26/2017, 5:20:02 PM,foo'
           

And with that, you should know everything necessary to create and manipulate arrays in JavaScript. Now go forth and array stuff up!

這樣一來,您應該了解在JavaScript中建立和操作數組所需的一切。 現在繼續排列數組!

有關數組的更多資訊: (More info about arrays:)

  • What in the world is a JavaScript array?

    JavaScript數組到底是什麼?

  • JavaScript array functions explained with examples

    JavaScript數組函數通過示例進行說明

  • Ultimate guide to Reduce

    終極還原指南

  • Ultimate guide to Map

    地圖終極指南

  • JavaScript array length explained

    JavaScript數組長度說明

有關回調函數的更多資訊 (More info about callback functions)

One thing you've undoubtedly noticed is that many of the array methods use callback functions. Check out these articles for more information about them:

您無疑注意到的一件事是,許多數組方法都使用回調函數。 檢視這些文章以擷取有關它們的更多資訊:

  • What is a callback function in JavaScript?

    什麼是JavaScript中的回調函數?

  • How to avoid callback hell

    如何避免回調地獄

翻譯自: https://www.freecodecamp.org/news/javascript-standard-objects-arrays/