0

I have this code...

var suitcase = {
    shirt: "Hawaiian"
};

var checkProp = function(obj, prop, val){
if(obj.hasOwnProperty(prop)){
    console.log(obj.prop);
} else {
    obj.prop = val;
    console.log(obj.prop);
}
};
checkProp("suitcase","shorts","blue");

and when I run it, it returns undefined. On the surface it looks fine. No syntax problems or similar things like that. What would I have to do to get this to work?

4

5 回答 5

0

suitcase is a var, not a string. Instead, it should read

checkProp(suitcase,'shorts','blue');
于 2013-02-07T15:34:36.007 回答
0

您有几个不同的选择,但我认为您的解决方案可能有效。它只是有一个小错误。在您调用您的函数时:

checkProp('suitcase', 'shorts', 'blue);

"suitcase"当它应该是一个对象时,您已将其定义为一个字符串。尝试修复它,看看它是否有效。

编辑:

您可以尝试的另一个选择是:

var checkProp = function(obj, prop, val){
    if(obj) {
        if(!obj[prop]) {
            obj[prop] = val;
        }
        if(window.console && window.console.log) {
            console.log(obj[prop]);
        }
    }
};
于 2013-02-07T15:37:03.213 回答
0
var suitcase = {
    shirt: "Hawaiian"
};

var checkProp = function(obj, prop, val){
    if(obj.hasOwnProperty(prop)){
        console.log(obj[prop]);
    } else {
        obj[prop] = val;
        console.log(obj[prop]);
    }
};
checkProp(suitcase,"shorts","blue");
于 2013-02-07T15:38:31.787 回答
0

通过它Object本身,而不是它的名字:

checkProp(suitcase,"shorts","blue");

另外,使用obj[prop]代替obj.prop.
(使用obj.prop,您访问的prop是对象的属性,字面意思,而不是您要查找的属性。)

除此之外,您的代码有效。不过,它可以像这样缩短:

var checkProp = function(obj, prop, val){
    obj[prop] = obj[prop] || val; // If obj[prop] exists, set it to itself (does nothing), otherwise, set it's content to `val`.
    console.log(obj.prop);
};
于 2013-02-07T15:34:59.260 回答
0

你想要的可能是 obj[prop] 而不是 obj.prop

于 2013-02-07T15:35:27.643 回答