如何从这样的数组中获取第一个元素:

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];

我试了一下:

alert($(ary).first());

但它会返回[object object]。所以我需要从数组中获取第一个元素它应该是元素first。


当前回答

try

var array= ['first', 'second', 'third', 'fourth', 'fifth'];
firstElement = array[array.length - array.length];

https://playcode.io/908187

其他回答

像这样

alert(ary[0])

另一个是给那些只关心真相的人的

ary.find(Boolean);

如果你想保持可读性,你可以在array . prototype中添加第一个函数:

Array.prototype.first = function () {
    return this[0];
};

A,那么你可以很容易地检索第一个元素:

[1, 2, 3].first();
> 1

只需使用ary.slice(0,1).pop();

In

var ary =[’first’,’second’,’third’’fourth’、’fifth’]; 游戏机。log(1º”+ ary slice(0.1)。pop ()); “2º”游戏机。log (+ ary slice(0.2)。pop ()); 游戏机。log(“3º”+ ary slice(0.3)。pop ()); 游戏机。log(“4º”+ ary slice(0.4)。pop ()); “5º”游戏机。log (+ ary slice(0.5)。pop ()); 游戏机log(“最后”+ ary。slice (- 1) pop ());

array.slice(START,END).pop();

在ES2015及以上版本中,使用数组解构:

Const arr = [42, 555, 666, 777] Const [first] = arr console.log(第一个)