如何从这样的数组中获取第一个元素:
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
我试了一下:
alert($(ary).first());
但它会返回[object object]。所以我需要从数组中获取第一个元素它应该是元素first。
如何从这样的数组中获取第一个元素:
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
我试了一下:
alert($(ary).first());
但它会返回[object object]。所以我需要从数组中获取第一个元素它应该是元素first。
当前回答
声明一个原型来获取第一个数组元素:
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];
其他回答
当数组下标从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'.
如果你将一个视图函数链接到数组,例如。
阵列。地图(i => i+1)。过滤器(i => i > 3)
想要在这些函数之后的第一个元素,你可以简单地添加。shift()它不会修改原始数组,这比数组更好。映射(i => i+1)。过滤器(=> I > 3)[0]
如果你想要一个数组的第一个元素而不修改原始元素,你可以使用array[0]或array.map(n=>n).shift()(没有映射,你将修改原始元素。顺便说一句,在这种情况下,我建议…[0]版本。
使用ES6解构
let [first] = [1,2,3];
哪个是一样的
let first = [1,2,3][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())
var ary = ["first", "second", "third", "fourth", "fifth"];
console.log(ary.shift());
//first
cosnole.log(ary);
// ["second", "third", "fourth", "fifth"]