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

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

我试了一下:

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

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


当前回答

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

其他回答

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

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

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

如果第一个元素被删除,索引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']));

声明一个原型来获取第一个数组元素:

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

然后把它用作:

var array = [0, 1, 2, 3];
var first = array.first();
var _first = [0, 1, 2, 3].first();

或者简单地说(:

first = array[0];

我更喜欢使用数组解构

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

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

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