识别 Javascript 对象中的最后一次迭代

发布于 2024-10-08 17:33:56 字数 251 浏览 0 评论 0原文

我有一个正在迭代的对象,

for (el in object) {
// Some work here
}

我想知道迭代内的最后一次迭代是什么时候,所以我可以做

for (el in object) {
// Some work here
if (last_iteration) {
// Do something
}
}

任何简单的方法来做到这一点?

I have an object that I'm iterating

for (el in object) {
// Some work here
}

I want to know when is the last iteration, inside the iteration, so I can do

for (el in object) {
// Some work here
if (last_iteration) {
// Do something
}
}

Any straightforward way to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我们的影子 2024-10-15 17:33:56

我知道我迟到了,但我刚刚遇到了这个问题并像这样修复了它:

let i = 0;
const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

for (el in object) {
   const last = i === length - 1; // true if last, false if not last
   console.log(i, el, last);
   i++;
}

更新:几年后,循环结束时的 i++ 确实让我很恼火。

const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

for (const [key, isLast] of Object.keys(object)
        .map((key, i) => [key, i === length - 1])) {
    console.log(key, isLast);
}

或者

const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

Object.keys(object)
    .map((key, i) => [key, i === length - 1]))
    .map(([key, isLast]) => {
        console.log(key, isLast);
    })

I know I'm late but I just ran into this and fixed it like this:

let i = 0;
const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

for (el in object) {
   const last = i === length - 1; // true if last, false if not last
   console.log(i, el, last);
   i++;
}

Update: A few years later, i++ at the end of a loop really irks me.

const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

for (const [key, isLast] of Object.keys(object)
        .map((key, i) => [key, i === length - 1])) {
    console.log(key, isLast);
}

or

const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

Object.keys(object)
    .map((key, i) => [key, i === length - 1]))
    .map(([key, isLast]) => {
        console.log(key, isLast);
    })

寄人书 2024-10-15 17:33:56

您可以执行以下操作:

var first = true;
var prev;

for (var el in object) {
  // Some work here
  if (first) {
    first = false;
  } else {
    doSomething(prev, object[prev]);
  }
  prev = el;
}

if (prev !== undefined) { // There was at least one element
  doSomethingElse(prev, object[prev]); // Prev is now last of all elements
}

以防万一您想以一种方式处理除最后一个元素之外的所有元素 (doSomething),并以另一种方式处理最后一个元素 (doSomethingElse) )。

如果您想以一种方式处理所有元素 (doSomething),并且只想对最后一个元素进行额外处理 (doSomethingExtra),您可以执行

var prev;

for (var el in object) {
  // Some work here
  doSomething(el, object[el]);
  prev = el;
}

if (prev !== undefined) { // There was at least one element
  doSomethingExtra(prev, object[prev]); // Prev is now last of all elements
}

以下操作 :更短的是,您可以通过重用 el 变量,即:

var el;

for (el in object) {
  // Some work here
  doSomething(el, object[el]);
}

if (el !== undefined) { // There was at least one element
  doSomethingExtra(el, object[el]); // El is now last of all elements
}

希望这有帮助。

You can do something like this:

var first = true;
var prev;

for (var el in object) {
  // Some work here
  if (first) {
    first = false;
  } else {
    doSomething(prev, object[prev]);
  }
  prev = el;
}

if (prev !== undefined) { // There was at least one element
  doSomethingElse(prev, object[prev]); // Prev is now last of all elements
}

This is in case you want to process all but the last element in one way (doSomething) and process the last element in another way (doSomethingElse).

If you want to process all the elements in one way (doSomething) and want to have extra processing for the last element only (doSomethingExtra), you can do:

var prev;

for (var el in object) {
  // Some work here
  doSomething(el, object[el]);
  prev = el;
}

if (prev !== undefined) { // There was at least one element
  doSomethingExtra(prev, object[prev]); // Prev is now last of all elements
}

To make it even shorter, you can do similar to what Török Gábor did in the gist he provided, by reusing el variable, i.e.:

var el;

for (el in object) {
  // Some work here
  doSomething(el, object[el]);
}

if (el !== undefined) { // There was at least one element
  doSomethingExtra(el, object[el]); // El is now last of all elements
}

Hope this helps.

她说她爱他 2024-10-15 17:33:56

如果键不是数字,则以下方法有效:

let anObject = {'one': 1, 'two': 2, 'three': 3, 'lastKey': 4};
let objectKeys = Object.keys(anObject);
let lastObjectKey = objectKeys.slice(-1).toString();
console.log(lastObjectKey); // 'lastKey'

Object.keys() 方法返回一个数组给定对象自己的可枚举属性名称,以与正常循环相同的顺序进行迭代。

带有导致重新排序的数字键的示例:

let anObject2 = {3: 3, 2: 2, 'notLastKey': 4, 1: 'lastKey'};
let objectKeys2 = Object.keys(anObject2);
console.log(objectKeys2); // ["1", "2", "3", "notLastKey"]
let lastObjectKey2 = objectKeys2.slice(-1).toString();
console.log(lastObjectKey2); // "notLastKey"

If the keys are not numerical, this works:

let anObject = {'one': 1, 'two': 2, 'three': 3, 'lastKey': 4};
let objectKeys = Object.keys(anObject);
let lastObjectKey = objectKeys.slice(-1).toString();
console.log(lastObjectKey); // 'lastKey'

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

Example with numerical keys causing reordering:

let anObject2 = {3: 3, 2: 2, 'notLastKey': 4, 1: 'lastKey'};
let objectKeys2 = Object.keys(anObject2);
console.log(objectKeys2); // ["1", "2", "3", "notLastKey"]
let lastObjectKey2 = objectKeys2.slice(-1).toString();
console.log(lastObjectKey2); // "notLastKey"

单挑你×的.吻 2024-10-15 17:33:56

请注意,只有当您要迭代的对象是数组(具有数字键)时,这才有效

var a = [1,2,3,4,5];

for (i in a) {
  if(a[+i+1] === undefined) 
    console.log('the last one is: ' + a[i]);
}


请注意,i 之前的 + 符号是必需的,因为如果省略,它将执行字符串连接,键结果为 01, 12、23

Note that this will only work if the object you are iterating over is an array (has numeric keys)

var a = [1,2,3,4,5];

for (i in a) {
  if(a[+i+1] === undefined) 
    console.log('the last one is: ' + a[i]);
}


Note that the + sign before i is necessary since if omitted, it will do a string concatenation, the keys resulting in 01, 12, 23, etc

感情废物 2024-10-15 17:33:56

如前所述,属性没有明显的顺序,因此最后枚举的属性只有在事后才知道。

var object = { a: 'b', c: 42 };
for ( var string in object ) ;
alert( object[string] );  // last property name is still here 

as said already, there is no distinct order for properties, so last enumerated property is only known afterwards.

var object = { a: 'b', c: 42 };
for ( var string in object ) ;
alert( object[string] );  // last property name is still here 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文