JavaScript数组长度说明

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/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值