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

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

我试了一下:

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

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


当前回答

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

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

其他回答

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

console.log(Object.keys(ary)[0]);

创建任意对象数组(req),然后简单地执行Object.keys(req)[0]来选择对象数组中的第一个键。

你可以使用find():

const first = array.find(Boolean)

或者如果你想要第一个元素,即使它是假的:

const first = array.find(() => true)

或者如果你想要第一个元素,即使它是假的,但如果它是空的或未定义的(更多信息):

const first = array.find(e => typeof e !== 'undefined')



加倍努力:

如果你关心可读性,但不想依赖于数值,你可以向Array添加一个first()函数。通过Object .define Property()来定义它,这减轻了直接修改内置Array对象原型的缺陷(在这里解释)。

性能非常好(find()在第一个元素之后停止),但它不是完美的或普遍可访问的(仅ES6)。更多背景信息请阅读@Selays的回答。

Object.defineProperty(Array.prototype, 'first', {
  value() {
    return this.find(e => true)     // or this.find(Boolean)
  }
})

要检索第一个元素,你现在可以这样做:

const array = ['a', 'b', 'c']
array.first()

> 'a'

片段以查看它的运行情况:

Object.defineProperty(Array.prototype, 'first', { 值(){ 返回this.find(布尔) } }) Console.log (['a', 'b', 'c'].first())

为什么要对一个普通JavaScript数组进行jquery化?使用标准JavaScript!

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
alert(ary[0]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

同时,

来源:bobince提供

@thomax的答案很好,但如果数组中的第一个元素为false或false-y(0,空字符串等),则会失败。除了undefined,最好返回true:

const arr = [];
arr[1] = '';
arr[2] = 'foo';

const first = arr.find((v) => { return (typeof v !== 'undefined'); });
console.log(first); // ''

你也可以使用.get(0):

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

来获取数组的第一个元素。