为简洁起见,我将使情况简短。
我正在循环一个对象,我需要找到可能的重复时间。下面是一个数据集的示例:
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...
我只是不明白为什么第一个条件不起作用,而其他条件起作用。我需要第一个来完成我的问题。
谢谢你的帮助。:)
发布于 2018-10-15 08:18:30
如果您试图在循环中访问showList[i + 1].time
的值,您将抛出一个错误,因为在最后一次迭代中showListi +1将是未定义的,并且某个undefined
的属性time将抛出一个错误
在最后一种情况下,它只是undefined
,但它没有中断
我认为你的问题是i + 1
,它在上一次迭代中并不存在
发布于 2018-10-15 12:46:11
您可以对其进行排序和缩减。
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);
发布于 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
https://stackoverflow.com/questions/52808141
复制相似问题