gpt4 book ai didi

javascript - 如何使用 Javascript 将迭代器索引号附加到数组中的每个项目?

转载 作者:行者123 更新时间:2023-11-30 12:31:07 25 4
gpt4 key购买 nike

如何将名为“Index”且值为字典索引的键附加到以下数组?在发生这种情况之前,应按时间戳对数组进行排序,以便 TimeStamp:111 排在第一位,TimeStamp:222 排在第二位,依此类推。

例如,原始数组如下所示

items = [
{Id: "01", Name: "A", Price: "1.00", Quantity: "1",TimeStamp:111},
{Id: "02", Name: "B", Price: "10.00", Quantity: "1",TimeStamp:222},
{Id: "04", Name: "C", Price: "9.50", Quantity: "10",TimeStamp:434},
{Id: "03", Name: "a", Price: "9.00", Quantity: "2",TimeStamp:545},
{Id: "06", Name: "b", Price: "100.00", Quantity: "2",TimeStamp:676},
{Id: "05",Name: "c", Price: "1.20", Quantity: "2",TimeStamp:777}
];

结果数组应该是这样的:

items = [
{Id: "01", Name: "A", Price: "1.00", Quantity: "1",TimeStamp:111,Index:1},
{Id: "02", Name: "B", Price: "10.00", Quantity: "1",TimeStamp:222,Index:2},
{Id: "04", Name: "C", Price: "9.50", Quantity: "10",TimeStamp:434,Index:3},
{Id: "03", Name: "a", Price: "9.00", Quantity: "2",TimeStamp:545,Index:4},
{Id: "06", Name: "b", Price: "100.00", Quantity: "2",TimeStamp:676,Index:5},
{Id: "05",Name: "c", Price: "1.20", Quantity: "2",TimeStamp:777,Index:6}
];

这是我的尝试:http://jsfiddle.net/chrisguzman/f7dnfrjf/我已经想出如何将一个项目附加到每个字典,但不知道如何附加其各自的迭代器。

另外,这里是 angular js(如果有办法用 angular 做的话加分):http://codepen.io/chriscruz/pen/GgjGvO?editors=101

最佳答案

索引从0开始,所以需要为每个索引添加+1,像这样

items.forEach(function (d, index) {
d.Index = index + 1;
});

演示:http://jsfiddle.net/f7dnfrjf/1/

Angular 演示:

  1. http://codepen.io/pen/ZYpRag - 索引显示为 2、3、5、6

  2. http://codepen.io/pen/zxKapG - 索引显示为 1, 2, 3, 4

关于javascript - 如何使用 Javascript 将迭代器索引号附加到数组中的每个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com