原文:JavaScript Array Length Explained

length 是 JavaScript 中数组的一个属性,用于返回或设置给定数组中元素的数量。

一个数组的 length 属性可以这样返回。

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

赋值运算符与 length 属性结合使用,可以像这样设置数组中的元素数量。

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

关于数组的更多内容

isArray() 方法

如果一个对象是一个数组,Array.isArray() 方法返回 true,否则返回 false

语法

Array.isArray(obj)

参数

obj 是要检查的对象。

MDN 链接 | MSDN 链接

示例

// 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.forEach

forEach 数组方法用于遍历数组中的每个项目。该方法在数组对象上被调用,并被传递给一个函数,该函数在数组中的每个项目上被调用。

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

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

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

回调函数也可以接受第二个参数,即索引,以备你需要引用数组中当前项的索引。

var 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.filter

array.prototype.reduce