简体   繁体   English

如何获取数组的第一个元素?

[英]How to get the first element of an array?

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] .但它会返回[object Object] So I need to get the first element from the array which should be the element 'first' .所以我需要从数组中获取第一个元素,它应该是元素'first'

像这样

alert(ary[0])

Why are you jQuery-ifying a vanilla JavaScript array?你为什么要 jQuery 化一个普通的 JavaScript 数组? Use standard JavaScript!使用标准 JavaScript!

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

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

Also,还, 需要更多 jQuery

Source , courtesy of bobince来源,由bobince提供

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] 是否确实存在。

Anther commonly used method is shift() but you should avoid using this for the purpose of accessing the first element.另一种常用的方法是shift()但你应该避免使用它来访问第一个元素。

Well, this method modifies the original array (removes the first item and returns it) but re-indexes what is left in the array to make it start from 0 (shifts everything down).好吧,这个方法修改了原始数组(删除第一项并返回它)但重新索引数组中剩余的内容以使其从 0 开始(将所有内容向下移动)。 Therefore the length of an array is reduced by one.因此,数组的长度减一。 There are good cases where you may need this, for example, to take the first customer waiting in the queue, but it is very inefficient to use this for the purpose of accessing the first element.在某些情况下,您可能需要它,例如,让第一个客户在队列中等待,但使用它来访问第一个元素是非常低效的。

In addition, this requires a perfect array with [0] index pointer intact, exactly as using [0];此外,这需要一个完整的 [0] 索引指针完整的数组,与使用 [0] 完全相同;

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".在某些情况下,第一个元素已被删除,例如 delete yourArray[0] 使您的数组留下“洞”。 Now the element at [0] is simply undefined, but you want to get the first "existing" element.现在 [0] 处的元素只是未定义的,但您想获得第一个“现有”元素。 I have seen many real world cases of this.我见过很多这样的真实案例。

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). find() 的优点是它的效率,因为它在达到满足条件的第一个值时退出循环(下面将详细介绍)。 (You can customize the condition to exclude null or other empty values too) (您也可以自定义条件以排除 null 或其他空值)

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.警告 filter() 并不是真正有效的方法(filter() 遍历所有元素)并创建另一个数组。 It is fine to use on small arrays as performance impact would be marginal, closer to using forEach, for example.可以在小型数组上使用,因为性能影响很小,例如更接近于使用 forEach。

Another one I have seen in some projects is splice() to get the first item in an array and then get it by index:我在一些项目中看到的另一个是splice()获取数组中的第一项,然后通过索引获取它:

var firstItem = yourArray.splice(0, 1)[0];

I am not sure why you would do that.我不确定你为什么要那样做。 This method won't solve the problem with holes in array (sparse array).此方法无法解决数组(稀疏数组)中的孔问题。 It is costly as it will re-index the array, and it returns an array and you have to access again to get the value.它的成本很高,因为它会重新索引数组,并且它会返回一个数组,您必须再次访问才能获取该值。 For example, if you delete first couple of elements and splice will return undefined instead of the first defined value from array.例如,如果您删除前几个元素,并且 splice 将返回 undefined 而不是数组中的第一个定义值。

(I see some people suggest using for...in loop to get the first element, but I would recommend against this method for...in should not be used to iterate over an Array where the index order is important because 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() 都保证元素的顺序,因此可以像上面一样安全使用。

Using ES6 destructuring使用 ES6 解构

let [first] = [1,2,3];

Which is the same as这与

let first = [1,2,3][0];

You can just use find() :您可以只使用find()

const first = array.find(Boolean)

Or if you want the first element even if it is falsy :或者如果你想要第一个元素,即使它是falsy

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

Or if you want the first element even if it is falsy but not if it is null or undefined ( more information ):或者,如果您想要第一个元素,即使它是虚假的,但如果它是 null 或未定义则不需要更多信息):

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



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.prototype by defining it with Object​.define​Property() which mitigates the pitfalls of modifying the built-in Array object prototype directly ( explained here ).如果您关心可读性但又不想依赖数字发生率,您可以通过使用Object​.define​Property()定义来向Array.prototype添加first() -函数,从而减轻修改内置函数的缺陷数组对象原型直接( 解释here )。

Performance is pretty good ( find() stops after the first element) but it isn't perfect or universally accessible (ES6 only).性能非常好( find()在第一个元素之后停止),但它并不完美或普遍可访问(仅限 ES6)。 For more background read @Selays answer .有关更多背景信息,请阅读@Selays answer

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

To retrieve the first element you are now able to do this:要检索第一个元素,您现在可以执行以下操作:

const 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() )

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']) );

If you want to preserve the readibility you 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: A 然后您可以轻松检索第一个元素:

[1, 2, 3].first();
> 1

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'
array.find(e => !!e);  // return the first element 

since "find" return the first element that matches the filter && !!e match any element.因为“查找”返回与过滤器匹配的第一个元素 && !!e匹配任何元素。

Note This works only when the first element is not a "Falsy" : null , false , NaN , "" , 0 , undefined注意这仅适用于第一个元素不是 "Falsy" : nullfalseNaN""0undefined

In ES2015 and above, using array destructuring:在 ES2015 及更高版本中,使用数组解构:

 const arr = [42, 555, 666, 777] const [first] = arr console.log(first)

只有在您使用 underscore.js ( http://underscorejs.org/ ) 的情况下,您才能执行以下操作:

_.first(your_array);

I know that people which come from other languages to JavaScript, looking for something like head() or first() to get the first element of an array, but how you can do that?我知道那些从其他语言转向 JavaScript 的人,正在寻找诸如head()first()之类的东西来获取数组的第一个元素,但你怎么能做到呢?

Imagine you have the array below:想象一下你有下面的数组:

const arr = [1, 2, 3, 4, 5];

In JavaScript, you can simply do:在 JavaScript 中,您可以简单地执行以下操作:

const first = arr[0];

or a neater, newer way is:或者更整洁、更新的方式是:

const [first] = arr;

But you can also simply write a function like...但是您也可以简单地编写一个函数,例如...

function first(arr) {
   if(!Array.isArray(arr)) return;
   return arr[0];
}

If using underscore, there are list of functions doing the same thing you looking for:如果使用下划线,则有一系列功能与您正在寻找的功能相同:

_.first 

_.head

_.take

Try alert(ary[0]);试试alert(ary[0]); . .

ES6 Spread operator + .shift() solution ES6 扩展运算符 + .shift() 解决方案

Using myArray.shift() you can get the 1st element of the array, but .shift() will modify the original array, so to avoid this, first you can create a copy of the array with [...myArray] and then apply the .shift() to this copy:使用myArray.shift()您可以获得数组的第一个元素,但.shift()会修改原始数组,因此为避免这种情况,首先您可以使用[...myArray]创建数组的副本,然后将.shift()应用于此副本:

 var myArray = ['first', 'second', 'third', 'fourth', 'fifth']; var first = [...myArray].shift(); console.log(first);

Method that works with arrays , and it works with objects too (beware, objects don't have a guaranteed order!).适用于数组的方法,它也适用于对象(请注意,对象没有保证的顺序!)。

I prefer this method the most, because original array is not modified.我最喜欢这种方法,因为原始数组没有被修改。

// In case of array
var arr = [];
arr[3] = 'first';
arr[7] = 'last';
var firstElement;
for(var i in arr){
    firstElement = arr[i];
    break;
}
console.log(firstElement);  // "first"

// In case of object
var obj = {
    first: 'first',
    last: 'last',
};

var firstElement;

for(var i in obj){
    firstElement = obj[i];
    break;
}

console.log(firstElement) // First;

I prefer to use Array Destructuring我更喜欢使用数组解构

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

Find the first element in an array using a filter:使用过滤器查找数组中的第一个元素:

In typescript:在打字稿中:

function first<T>(arr: T[], filter: (v: T) => boolean): T {
    let result: T;
    return arr.some(v => { result = v; return filter(v); }) ? result : undefined;
}

In plain javascript:在纯 JavaScript 中:

function first(arr, filter) {
    var result;
    return arr.some(function (v) { result = v; return filter(v); }) ? result : undefined;
}

And similarly, indexOf:同样,indexOf:

In typescript:在打字稿中:

function indexOf<T>(arr: T[], filter: (v: T) => boolean): number {
    let result: number;
    return arr.some((v, i) => { result = i; return filter(v); }) ? result : undefined;
}

In plain javascript:在纯 JavaScript 中:

function indexOf(arr, filter) {
    var result;
    return arr.some(function (v, i) { result = i; return filter(v); }) ? result : undefined;
}

另一个只关注真实元素的人

ary.find(Boolean);

Just use ary.slice(0,1).pop();只需使用ary.slice(0,1).pop();

In

 var ary = ['first', 'second', 'third', 'fourth', 'fifth']; console.log("1º "+ary.slice(0,1).pop()); console.log("2º "+ary.slice(0,2).pop()); console.log("3º "+ary.slice(0,3).pop()); console.log("4º "+ary.slice(0,4).pop()); console.log("5º "+ary.slice(0,5).pop()); console.log("Last "+ary.slice(-1).pop());

array.slice(START,END).pop(); array.slice(START,END).pop();

Why not account for times your array might be empty?为什么不考虑您的数组可能为空的时间?

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

When there are multiple matches, JQuery's .first() is used for fetching the first DOM element that matched the css selector given to jquery.当有多个匹配项时,JQuery 的 .first() 用于获取与提供给 jquery 的 css 选择器匹配的第一个 DOM 元素。

You don't need jQuery to manipulate javascript arrays.您不需要 jQuery 来操作 javascript 数组。

You could also use .get(0):您也可以使用 .get(0):

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

To get the first element of the array.获取数组的第一个元素。

Declare a prototype to get first array element as:声明一个原型以获取第一个数组元素:

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

Then use it as:然后将其用作:

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

Or simply (:或者简单地说(:

first = array[0];

The previous examples work well when the array index begins at zero.当数组索引从零开始时,前面的示例运行良好。 thomax's answer did not rely on the index starting at zero, but relied on Array.prototype.find to which I did not have access. thomax 的答案不依赖于从零开始的索引,而是依赖于我无法访问的Array.prototype.find The following solution using jQuery $.each worked well in my case.以下使用jQuery $.each的解决方案在我的情况下效果很好。

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'.

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

If you're chaining a view functions to the array eg如果您将视图函数链接到数组,例如

array.map(i => i+1).filter(i => i > 3)

And want the first element after these functions you can simply add a .shift() it doesn't modify the original array , its a nicer way then array.map(i => i+1).filter(=> i > 3)[0]并且想要这些函数之后的第一个元素,您可以简单地添加一个.shift()它不会修改原始array ,它是一种更好的方式然后array.map(i => i+1).filter(=> i > 3)[0]

If you want the first element of an array without modifying the original you can use array[0] or array.map(n=>n).shift() (without the map you will modify the original. In this case btw i would suggest the ..[0] version.如果您想要数组的第一个元素而不修改原始元素,您可以使用array[0]array.map(n=>n).shift() (没有地图,您将修改原始元素。在这种情况下,我会建议..[0]版本。

You can do it by lodash _.head so easily.你可以很容易地通过lodash _.head做到这一点。

 var arr = ['first', 'second', 'third', 'fourth', 'fifth']; console.log(_.head(arr));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

try尝试

var array= ['first', 'second', 'third', 'fourth', 'fifth'];
firstElement = array[array.length - array.length];

https://playcode.io/908187 https://playcode.io/908187

@NicoLwk You should remove elements with splice, that will shift your array back. @NicoLwk您应该使用拼接删除元素,这会将您的数组移回。 So:所以:

var a=['a','b','c'];
a.splice(0,1);
for(var i in a){console.log(i+' '+a[i]);}

Use this to split character in javascript.使用它来分割 javascript 中的字符。

var str = "boy, girl, dog, cat";
var arr = str.split(",");
var fst = arr.splice(0,1).join("");
var rest = arr.join(",");
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];

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

Make any Object array ( req ), then simply do Object.keys(req)[0] to pick the first key in the Object array.制作任何 Object 数组 ( req ),然后简单地执行Object.keys(req)[0]来选择 Object 数组中的第一个键。

Using ES6.使用 ES6。

let arr = [22,1,4,55,7,8,9,3,2,4];

let {0 : first ,[arr.length - 1] : last} = arr;
console.log(first, last);

or或者

let {0 : first ,length : l, [l - 1] : last} = [22,1,4,55,7,8,9,3,2,4];
console.log(first, last);
var ary = ["first", "second", "third", "fourth", "fifth"];
console.log(ary.shift());
//first

@thomax 's answer is pretty good, but will fail if the first element in the array is false or false-y (0, empty string, etc.). @thomax 的答案非常好,但如果数组中的第一个元素为 false 或 false-y(0、空字符串等),则会失败。 Better to just return true for anything other than undefined:最好只为未定义以外的任何内容返回 true:

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

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

ES6 easy: ES6 简单:

let a = []
a[7] = 'A'
a[10] = 'B'

let firstValue = a.find(v => v)
let firstIndex = a.findIndex(v => v)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM