我有一个对象数组。我需要获取最后一个对象的类型(在此示例中为“形状”),将其删除,然后找到先前在数组中具有相同类型(例如“形状”)的对象的索引。
var fruits = [
{
shape: round,
name: orange
},
{
shape: round,
name: apple
},
{
shape: oblong,
name: zucchini
},
{
shape: oblong,
name: banana
},
{
shape: round,
name: grapefruit
}
]
// What's the shape of the last fruit
var currentShape = fruits[fruits.length-1].shape;
// Remove last fruit
fruits.pop(); // grapefruit removed
// Find the index of the last round fruit
var previousInShapeType = fruits.lastIndexOf(currentShape);
// should find apple, index = 1
所以,显然这个例子中的类型将是“round”。但我不是在寻找一个数组值为“round”的结果。我要找的是水果形状 = 圆形的地方。
var previousInShapeType = fruits.lastIndexOf(fruits.shape = currentShape);
但仅仅使用那个并不起作用。我确定我错过了一些简单的东西。如何找到数组中最后一个形状为“round”的对象?