[英]Checking if a key exists in a JS object
我有以下 JavaScript object:
var obj = {
"key1" : val,
"key2" : val,
"key3" : val
}
有没有办法检查数组中是否存在一个键,类似于这个?
testArray = jQuery.inArray("key1", obj);
不起作用。
我必须像这样遍历 obj 吗?
jQuery.each(obj, function(key,val)){}
那不是一个 jQuery 对象,它只是一个对象。
您可以使用 hasOwnProperty 方法来检查密钥:
if (obj.hasOwnProperty("key1")) {
...
}
var obj = {
"key1" : "k1",
"key2" : "k2",
"key3" : "k3"
};
if ("key1" in obj)
console.log("has key1 in obj");
================================================== ========================
访问另一个键的子键
var obj = {
"key1": "k1",
"key2": "k2",
"key3": "k3",
"key4": {
"keyF": "kf"
}
};
if ("keyF" in obj.key4)
console.log("has keyF in obj");
上面的答案很好。 但这也很好,很有用。
!obj['your_key'] // if 'your_key' not in obj the result --> true
它适用于 if 语句中的短代码风格:
if (!obj['your_key']){
// if 'your_key' not exist in obj
console.log('key not in obj');
} else {
// if 'your_key' exist in obj
console.log('key exist in obj');
}
注意:如果您的键等于 null 或 "",您的 "if" 语句将是错误的。
obj = {'a': '', 'b': null, 'd': 'value'}
!obj['a'] // result ---> true
!obj['b'] // result ---> true
!obj['c'] // result ---> true
!obj['d'] // result ---> false
因此,检查 obj 中是否存在键的最佳方法是: 'a' in obj
map.has(key)
是ECMAScript 2015最新的检查映射中键是否存在的方法。 有关完整的详细信息, 请参阅此内容。
你可以试试这个:
const data = {
name : "Test",
value: 12
}
if("name" in data){
//Found
}
else {
//Not found
}
最简单的方法是
const obj = { a: 'value of a', b: 'value of b', c: 'value of c' }; if(obj.a){ console.log(obj.a); }else{ console.log('obj.a does not exist'); }
使用hasOwnProperty()
,
if (!obj.hasOwnProperty(key)) {
}
例如:
const object1 = {
one : 'value of one',
two : 'value of two',
three : 'value of three',
};
console.log(object1.hasOwnProperty('one'));
// expected output: true
console.log(object1.hasOwnProperty('value of one'));
// expected output: false
console.log(object1.hasOwnProperty('four'));
// expected output: false
这对我来说就像一个魅力。 我在一个foreach
function 里面这不起作用obj.hasOwnProperty("key1")
还有这个"key1" in obj
let $schedule = {lesson:'asd',age:'sad'}
$schedules.forEach(function(e) {
if (e['lesson']) {
$title = e.lesson.lesson_name;
} else {
$title = 'No lesson Attached';
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.