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

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

我试了一下:

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

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


当前回答

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

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

其他回答

@NicoLwk你应该用splice删除元素,这会把你的数组移回来。所以:

var a=['a','b','c'];
a.splice(0,1);
for(var i in a){console.log(i+' '+a[i]);}

当数组下标从0开始时,前面的示例工作得很好。thomax的答案并不依赖于从0开始的索引,而是依赖于我没有访问权限的Array.prototype.find。下面的解决方案使用jQuery $。对我来说,每一种都很有效。

let haystack = {100: 'first', 150: 'second'},
    found = null;

$.each(haystack, function( index, value ) {
    found = value;  // Save the first array element for later.
    return false;  // Immediately stop the $.each loop after the first array element.
});

console.log(found); // Prints 'first'.

我更喜欢使用数组解构

const [first, second, third] = ["Laide", "Gabriel", "Jets"];
console.log(first);  // Output: Laide
console.log(second); // Output: Gabriel
console.log(third);  // Output: Jets

只需使用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();

为什么不考虑数组可能为空的时间呢?

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
first = (array) => array.length ? array[0] : 'no items';
first(ary)
// output: first

var ary = [];
first(ary)
// output: no items