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 the number of elements in an array like so.
赋值运算符与length属性一起可用于像这样设置数组中元素的数量。
let cars = ["Saab", "BMW", "Volvo"]; cars.length = 2; console.log(cars.length); // 2
有关数组的更多信息: (More info about arrays:)
isArray()方法 (isArray() method)
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要检查的对象。
MDN link | MSDN link
MDN链接 | MSDN链接
Examples:
例子:
// 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 (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”数组方法用于遍历数组中的每个项目。 该方法在对象数组上调用,并传递给在数组中每个项目上调用的函数。
var 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.
如果您需要引用数组中当前项目的索引,则回调函数还可以使用索引的第二个参数。
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'
进一步了解数组: (Further reading about arrays:)
array.prototype.filter
array.prototype.filter
array.prototype.reduce
array.prototype.reduce
翻译自: https://www.freecodecamp.org/news/javascript-array-length/
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/199169.html原文链接:https://javaforall.net
