【发布时间】:2015-10-21 20:42:37
【问题描述】:
我有一个对象数组。我需要获取最后一个对象的对象类型(本例中为“形状”),将其删除,然后在具有相同类型的数组中找到前一个对象的索引,例如“形状”。
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”的数组值。我正在寻找 fruits.shape = round 的位置。
var previousInShapeType = fruits.lastIndexOf(fruits.shape = currentShape);
但是仅仅使用它是行不通的。我确定我错过了一些简单的东西。如何在数组中找到对象形状 = 圆形的最后一项?
【问题讨论】:
-
你是在寻找这个对象的索引还是只是对象本身?
-
实际上,两者都可以。如果我有索引,我可以访问该对象。
标签: javascript arrays