本文介绍了如何按值删除javascript对象项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,使用以下对象:

var fruits = {
    "red" : "apple",
    "blue" : "blueberry",
    "yellow" : "banana"
}

我知道我可以使用 deletefruit ["red"] 通过键名将其删除,但是如何通过水果名删除对象项?

I know I can use delete fruits["red"] to remove it by the key name, but how could I delete the object item by the fruit name?

推荐答案

您尝试过这种方法吗?

function deleteByValue(val) {
    for(var f in fruits) {
        if(fruits[f] == val) {
            delete fruits[f];
        }
    }
}

根据Rocket的评论,您可能需要检查 hasOwnProperty 以确保您没有删除对象原型的成员:

And as per Rocket's comment, you might want to check hasOwnProperty to make sure you aren't deleting members of the object's prototype:

function deleteByValue(val) {
    for(var f in fruits) {
        if(fruits.hasOwnProperty(f) && fruits[f] == val) {
            delete fruits[f];
        }
    }
}

这篇关于如何按值删除javascript对象项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 18:39