Javascript 如何获取数组的第一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4090491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the first element of an array?
提问by MacMac
How do you get the first element from an array like this:
你如何从这样的数组中获取第一个元素:
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
I tried this:
我试过这个:
alert($(ary).first());
But it would return [object Object]
. So I need to get the first element from the array which should be the element 'first'
.
但它会返回[object Object]
。所以我需要从数组中获取第一个元素,它应该是 element 'first'
。
回答by John Hartsock
like this
像这样
alert(ary[0])
回答by Matt Ball
Why are you jQuery-ifying a vanilla JavaScript array? Use standard JavaScript!
你为什么要用 jQuery 化一个普通的 JavaScript 数组?使用标准 JavaScript!
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
alert(ary[0]);
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
回答by Selay
Some of ways below for different circumstances.
下面的一些方法针对不同的情况。
In most normal cases, the simplest way to access the first element is by
在大多数正常情况下,访问第一个元素的最简单方法是通过
yourArray[0]
but this requires you to check if [0] actually exists.
但这需要您检查 [0] 是否确实存在。
There are real world cases where you don't care about the original array, and don't want to check if index exists, you want just to get the first element or undefined inline.
在现实世界中,您不关心原始数组,也不想检查索引是否存在,只想获取第一个元素或未定义的内联元素。
In this case, you can use shift()method to get the first element, but be cautious that this method modifies the original array (removes the first item and returns it). Therefore the length of an array is reduced by one. This method can be used in inline cases where you just need to get the first element, but you dont care about the original array.
在这种情况下,您可以使用shift()方法来获取第一个元素,但要注意此方法会修改原始数组(删除第一项并返回它)。因此数组的长度减一。此方法可用于内联情况,即您只需要获取第一个元素,但您不关心原始数组。
yourArray.shift()
The important thing to know is that the two above are only an option if your array starts with a [0] index.
要知道的重要一点是,如果您的数组以 [0] 索引开头,则上述两个只是一个选项。
There are cases where the first element has been deleted, example with, delete yourArray[0] leaving your array with "holes". Now the element at [0] is simply undefined, but you want to get the first "existing" element. I have seen many real world cases of this.
在某些情况下,第一个元素已被删除,例如, delete yourArray[0] 使您的数组带有“孔”。现在 [0] 处的元素只是未定义,但您想要获得第一个“现有”元素。我见过很多这样的现实世界案例。
So, assuming we have no knowledge of the array and the first key (or we know there are holes), we can still get the first element.
所以,假设我们不知道数组和第一个键(或者我们知道有洞),我们仍然可以获得第一个元素。
You can use find()to get the first element.
您可以使用find()来获取第一个元素。
The advantage of find() is its efficiency as it exits the loop when the first value satisfying the condition is reached (more about this below). (You can customize the condition to exclude null or other empty values too)
find() 的优点是它的效率,因为它在达到满足条件的第一个值时退出循环(更多关于此的内容见下文)。(您也可以自定义条件以排除空值或其他空值)
var firstItem = yourArray.find(x=>x!==undefined);
I'd also like to include filter()here as an option to first "fix" the array in the copy and then get the first element while keeping the the original array intact (unmodified).
我还想在此处包含filter()作为首先“修复”副本中的数组的选项,然后在保持原始数组完整(未修改)的同时获取第一个元素。
Another reason to include filter() here is that it existed before find() and many programmers have already been using it (it is ES5 against find() being ES6).
在这里包含 filter() 的另一个原因是它存在于 find() 之前并且许多程序员已经在使用它(它是 ES5,而 find() 是 ES6)。
var firstItem = yourArray.filter(x => typeof x!==undefined).shift();
Warning that filter() is not really an efficient way (filter() runs through all elements) and creates another array. It is fine to use on small arrays as performance impact would be marginal, closer to using forEach, for example.
警告 filter() 并不是真正有效的方法(filter() 遍历所有元素)并创建另一个数组。可以在小型阵列上使用,因为性能影响很小,例如更接近于使用 forEach。
(I see some people recommend using for...in loop to get the first element, but I would recommend against this method because for...in should not be used to iterate over an Array where the index order is importantbecause it doesn't guarantee the order although you can argue browsers mostly respect the order.By the way, forEach doesn't solve the issue as many suggest because you cant break it and it will run through all elements. You would be better off using a simple for loop and by checking key/value
(我看到有些人推荐使用 for...in 循环来获取第一个元素,但我建议不要使用这种方法,因为for...in 不应该用于迭代索引顺序很重要的数组,因为它不不保证顺序,尽管您可以争辩说浏览器大多尊重顺序。顺便说一句,forEach 并没有像许多人建议的那样解决问题,因为您无法打破它并且它将贯穿所有元素。您最好使用简单的for 循环并通过检查键/值
Both find() and filter() guarantee the order of elements, so are safe to use as above.
find() 和 filter() 都保证元素的顺序,因此可以安全地使用如上。
回答by NicoLwk
Element of index 0 may not exist if the first element has been deleted:
如果第一个元素已被删除,则索引 0 的元素可能不存在:
let a = ['a', 'b', 'c'];
delete a[0];
for (let i in a) {
console.log(i + ' ' + a[i]);
}
Better way to get the first element without jQuery:
在没有 jQuery 的情况下获取第一个元素的更好方法:
function first(p) {
for (let i in p) return p[i];
}
console.log( first(['a', 'b', 'c']) );
回答by Flavien Volken
Using ES6 destructuring
使用 ES6 解构
let [first] = [1,2,3];
Which is the same as
这与
let first = [1,2,3][0];
回答by eliocs
If you want to preserve the readibilityyou could always add a first function to the Array.protoype
:
如果你想保持可读性,你总是可以添加第一个函数到Array.protoype
:
Array.prototype.first = function () {
return this[0];
};
A then you could easily retrieve the first element:
然后您可以轻松检索第一个元素:
[1, 2, 3].first();
> 1
回答by leonheess
You can just use find()
:
你可以只使用find()
:
let first = array.find(Boolean);
Orif you want the first element even if it is falsy:
或者如果你想要第一个元素,即使它是假的:
let first = array.find(e => true);
Going the extra mile:
加倍努力:
If you care about readability but don't want to rely on numeric incidences you could add a first()
-function to Array.protoype
by defining it with Object?.define?Property()
which mitigates the pitfalls of modifying the built-in Array object prototype directly (explained here).
如果您关心可读性但不想依赖数字first()
关联,您可以Array.protoype
通过定义它来添加一个- 函数,以Object?.define?Property()
减轻直接修改内置 Array 对象原型的陷阱(解释here)。
Performance is pretty good (find()
stops after the first element) but it isn't perfect or universally accessible (ES6 only). For more background read @Selays answer.
性能非常好(find()
在第一个元素之后停止),但它并不完美或普遍可访问(仅限 ES6)。有关更多背景信息,请阅读@Selays 答案。
Object.defineProperty(Array.prototype, 'first', {
value() {
return this.find(e => true); // or this.find(Boolean)
}
});
Then to retrieve the first element you can do:
然后要检索您可以执行的第一个元素:
let array = ['a', 'b', 'c'];
array.first();
> 'a'
Snippet to see it in action:
片段以查看它的运行情况:
Object.defineProperty(Array.prototype, 'first', {
value() {
return this.find(Boolean);
}
});
console.log( ['a', 'b', 'c'].first() );
回答by thomax
If your array is not guaranteed to be populated from index zero, you can use Array.prototype.find()
:
如果您的数组不能保证从索引零开始填充,您可以使用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'
回答by Abdennour TOUMI
array.find(e => !!e); // return the first element
since "find" return the first element that matches the filter && !!e
match any element.
因为“find”返回匹配过滤器的第一个元素 &&!!e
匹配任何元素。
NoteThis works only when the first element is not a "Falsy" : null
, false
, NaN
, ""
, 0
, undefined
注意这仅在第一个元素不是“Falsy”时才有效:null
, false
, NaN
, ""
, 0
,undefined
回答by thejh
Try alert(ary[0]);
.
试试alert(ary[0]);
。