var json = {"key1":"val1","key2":"val2","key3":"val3"};
if(json.hasOwnProperty("key1")){
console.log(json["key1]);
转自:
https://www.cnblogs.com/xiaozhouyuxiaohou/p/9945492.html
如何
判断
传过来的
JSON
数据中,某个字段
是否
存在,
1.obj[“
key
”] != undefined
这种有缺陷,如果这个
key
定义了,并且就是很2的赋
值
为undefined,那么这句就会出问题了。
2.!(“
key
” in obj)
3.obj.hasOwnProperty(“
key
”)
这两种方法就比较好了,推荐使用。
答案原文:
Actually, checking for undefined-ness is not an accurate way of testing whether a
key
exists. What if the
key
exists but th
var
json
= {"
key
1":"val1","
key
2":"val2","
key
3":"val3"};
if(
json
.hasOwnProperty("
key
1")){
console.log(
json
["
key
1]);
resoult:
转载于:https://www.cnblogs.com/xiaozhouyuxiaohou/p...
在JavaScript中,
判断
JSON
对象
是否
包含某个
key
,你可以使用`in`运算符或`hasOwnProperty()`方法。这里有两个示例:
1. 使用`in`运算符:
```javascript
let obj = { name: 'John', age: 30 };
if ('name' in obj) {
console.log('
对象
包含 "name" 键');
} else {
console.log('
对象
不包含 "name" 键');
2. 使用`hasOwnProperty()`方法:
```javascript
if (obj.hasOwnProperty('name')) {
console.log('
对象
包含 "name" 键');
} else {
console.log('
对象
不包含 "name" 键');
这两个方法的区别在于,`in`会检查原型链上的属性,而`hasOwnProperty()`只检查当前
对象
自身的属性。
如果你想创建一个通用的方法来检测任意键
是否
存在,可以这样写:
```javascript
function has
Key
(obj,
key
) {
return obj.hasOwnProperty(
key
) || Object.prototype.hasOwnProperty.call(obj,
key
);
let obj = { name: 'John', age: 30 };
console.log(has
Key
(obj, 'name')); // true
console.log(has
Key
(obj, 'address')); // false(如果不存在该键)
在这个`has
Key
`函数里,我们首先用`hasOwnProperty`检查,然后通过`Object.prototype.hasOwnProperty.call`扩展到原型链上。