[英]How to create a function to check for property of an object in javascript, and set it if it's not there
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?
我要做什么才能使它正常工作?
suitcase
is a var, not a string. suitcase
是可变的,不是字符串。 Instead, it should read 相反,它应该显示为
checkProp(suitcase,'shorts','blue');
Pass the Object
itself, not it's name: 传递
Object
本身,而不是名称:
checkProp(suitcase,"shorts","blue");
Also, use obj[prop]
instead of obj.prop
. 另外,请使用
obj[prop]
而不是obj.prop
。
(With obj.prop
, you're accessing the prop
property of the object, literally, not the property you're looking for.) (使用
obj.prop
,您访问的是对象的prop
属性,而不是您要查找的属性。)
Other than that, your code works. 除此之外,您的代码还可以工作。 It could be shortened like this, though:
可以这样缩短它:
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);
};
您想要的可能是obj [prop]而不是obj.prop
You have a few different options but I think your solution may work. 您有几种选择,但我认为您的解决方案可能会起作用。 It just has a small error.
它只是有一个小错误。 In your call to your function:
在调用函数时:
checkProp('suitcase', 'shorts', 'blue);
You have "suitcase"
defined as a string when it should be an object. 当您将
"suitcase"
定义为字符串时,它应该是一个对象。 Try fixing that and see if it works. 尝试修复该问题,然后查看是否可行。
Edit: 编辑:
Another option you could try would be this: 您可以尝试的另一种选择是:
var checkProp = function(obj, prop, val){
if(obj) {
if(!obj[prop]) {
obj[prop] = val;
}
if(window.console && window.console.log) {
console.log(obj[prop]);
}
}
};
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.