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

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

我试了一下:

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

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


当前回答

var ary = ["first", "second", "third", "fourth", "fifth"];
console.log(ary.shift());
//first
cosnole.log(ary);
// ["second", "third", "fourth", "fifth"]

其他回答

一个香草的JS代码,没有jQuery,没有库,没有什么..: P . .如果数组下标不是从0开始,它也会工作。

var必要=['第一次','第二','第三',' 4 ',' 5 ']; console.log (Object.values(必要)[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())

像这样

alert(ary[0])
array.find(e => !!e);  // return the first element 

因为"find"返回第一个匹配过滤器的元素&& !!E匹配任何元素。

注意:只有当第一个元素不是“Falsy”时才有效:null, false, NaN, "", 0, undefined

如果第一个元素被删除,索引0的元素可能不存在:

Let a = ['a', 'b', 'c']; 删除一个[0]; 对于(令I在a中){ Console.log (i + ' ' + a[i]); }

更好的方法得到第一个元素没有jQuery:

函数优先(p) { For (let I in p) return p[I]; } Console.log (first(['a', 'b', 'c']));