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

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

我试了一下:

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

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


当前回答

只有在使用underscore.js (http://underscorejs.org/)的情况下,你可以这样做:

_.first(your_array);

其他回答

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

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

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

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

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

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

如果你的数组不能保证从索引0填充,你可以使用array .prototype.find():

var elements = []
elements[1] = 'foo'
elements[2] = 'bar'

var first = function(element) { return !!element }    
var gotcha = elements.find(first)

console.log(a[0]) // undefined
console.log(gotcha) // 'foo'

当数组下标从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'.

我知道从其他语言学习到JavaScript的人,会寻找head()或first()来获取数组的第一个元素,但你怎么做呢?

假设你有如下数组:

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

在JavaScript中,你可以简单地做:

const first = arr[0];

或者一种更整洁、更新的方式是:

const [first] = arr;

但你也可以简单地写一个函数…

function first(arr) {
   if(!Array.isArray(arr)) return;
   return arr[0];
}

如果使用下划线,有一个函数列表做相同的事情,你正在寻找:

_.first 

_.head

_.take