我有一组对象。我需要获取最后一个对象的对象类型(本例中为“shape”),将其删除,然后在数组中找到具有相同类型(例如“shape”)的前一个对象的索引。
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”的数组值。我正在寻找 fruits.shape = round 的位置。
var previousInShapeType = fruits.lastIndexOf(fruits.shape = currentShape);
但是仅仅使用它是行不通的。我确定我错过了一些简单的东西。如何找到数组中对象形状 = 圆形的最后一项?
原文由 Graeck 发布,翻译遵循 CC BY-SA 4.0 许可协议
您还可以通过数组向后循环。
小提琴:http: //jsfiddle.net/vonn9xhm/