首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >一个我不理解的JavaScript怪癖。循环遍历对象数组

一个我不理解的JavaScript怪癖。循环遍历对象数组
EN

Stack Overflow用户
提问于 2018-10-15 08:00:59
回答 3查看 80关注 0票数 -1

为简洁起见,我将使情况简短。

我正在循环一个对象,我需要找到可能的重复时间。下面是一个数据集的示例:

let showList = [ 
    { name: 'Little Death Club', time: 8, length: 2, price: 10 },
    { name: 'Courtney Act', time: 6, length: 1, price: 10},
    { name: 'Reversible', time: 7, length: 1, price: 12 }
]

基本上,我得到了一个错误,如下所示:我循环遍历对象数组,并有一个条件,如下所示。该条件用于查找可能的重复时间:

showList[i + 1].time)  -->>  This throws an error.

showList[i].time)  -->> However this works.

showList[i + 1])  -->> AND this works...

我只是不明白为什么第一个条件不起作用,而其他条件起作用。我需要第一个来完成我的问题。

谢谢你的帮助。:)

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-10-15 08:18:30

如果您试图在循环中访问showList[i + 1].time的值,您将抛出一个错误,因为在最后一次迭代中showListi +1将是未定义的,并且某个undefined的属性time将抛出一个错误

在最后一种情况下,它只是undefined,但它没有中断

我认为你的问题是i + 1,它在上一次迭代中并不存在

票数 0
EN

Stack Overflow用户

发布于 2018-10-15 12:46:11

您可以对其进行排序和缩减。

Array.sort()

Array.reduce()

let showList = [
    { name: 'Little Death Club', time: 8, length: 2, price: 10 },
    { name: 'Courtney Act', time: 6, length: 1, price: 10 },
    { name: 'Reversible', time: 7, length: 1, price: 12 },
    { name: 'Test', time: 7, length: 1, price: 12 }
].sort((a, b) => a.time - b.time).reduce((acc, cur, idx, arr) => {
    let prev = arr[idx - 1];
    if (prev && prev.time === cur.time)
        acc.push(prev, cur);
    return acc;
}, []);
console.log(showList);

票数 0
EN

Stack Overflow用户

发布于 2018-10-15 08:06:16

//showList[i + 1].time)
undefined
//showList[i].time)
undefined
//showList[i + 1])
undefined
let showList = [ 
    { name: 'Little Death Club', time: 8, length: 2, price: 10 },
    { name: 'Courtney Act', time: 6, length: 1, price: 10},
    { name: 'Reversible', time: 7, length: 1, price: 12 }
]

undefined
showList[i + 1].time)
VM194:1 Uncaught SyntaxError: Unexpected token )
showList[i].time)
VM197:1 Uncaught SyntaxError: Unexpected token )
showList[i + 1])
VM200:1 Uncaught SyntaxError: Unexpected token )

showList[i + 1].time
VM1049:1 Uncaught TypeError: Cannot read property 'time' of undefined
    at <anonymous>:1:17
(anonymous) @ VM1049:1
showList[i].time
VM1061:1 Uncaught TypeError: Cannot read property 'time' of undefined
    at <anonymous>:1:13
(anonymous) @ VM1061:1
showList[i]
undefined
i
undefined
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52808141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档