检查键是否存在于JavaScript对象中?

如何检查JavaScript对象或数组中是否存在特定键?

如果密钥不存在,而我尝试访问它,它将返回false吗? 还是抛出错误?


#1楼

它将返回undefined

 var aa = {hello: "world"}; alert( aa["hello"] ); // popup box with "world" alert( aa["goodbye"] ); // popup box with "undefined" 

undefined是一个特殊的常数值。 所以你可以说,例如

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

这可能是检查丢失键的最佳方法。 但是,正如下面的评论中指出的那样,从理论上讲,您可能希望undefined实际值。 我从来不需要这样做,也无法想出我为什么要使用的临时原因,但是为了完整起见,您可以使用in运算符

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}

#2楼

检查不确定性不是测试密钥是否存在的准确方法。 如果键存在但值实际上undefined怎么办?

var obj = { key: undefined };
obj["key"] !== undefined // false, but the key exists!

您应该改用in运算子:

"key" in obj // true, regardless of the actual value

如果要检查键是否不存在,请记住使用括号:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

或者,如果要特别测试对象实例的属性(而不是继承的属性),请使用hasOwnProperty

obj.hasOwnProperty("key") // true

有关in中的hasOwnProperty和key undefined的方法之间的性能比较,请参阅此基准


#3楼

"key" in obj

可能只测试与数组键非常不同的对象属性值


#4楼

检查javascript对象中是否存在属性的三种方法:

  1. !! obj.theProperty
    将值转换为布尔值。 对于除“ false”值以外的所有值,返回TRUE
  2. obj中的“ theProperty”
    如果该属性存在,则无论其值如何(即使为空)也将返回true
  3. obj.hasOwnProperty('theProperty')
    不检查原型链。 (由于所有对象都具有'toString'方法,因此1和2将对其返回true,而3可对其返回false。)

参考:

http://book.mixu.net/node/ch5.html


#5楼

快速回答

如何检查JavaScript对象或数组中是否存在特定键? 如果密钥不存在,而我尝试访问它,它将返回false吗? 还是抛出错误?

使用(关联)数组样式或对象样式直接访问缺少的属性将返回未定义的常量。

慢而可靠运营商和hasOwnProperty方法

正如人们在这里已经提到的那样,您可以拥有一个对象,该对象的属性与“未定义”常量关联。

 var bizzareObj = {valid_key:  undefined};

在这种情况下,您将必须使用hasOwnPropertyin运算符来知道密钥是否确实存在。 但是, 但是价格是多少?

所以,我告诉你...

operator和hasOwnProperty中的in是在Javascript中使用属性描述符机制的“方法”(类似于Java语言中的Java反射)。

http://www.ecma-international.org/ecma-262/5.1/#sec-8.10

“属性描述符”类型用于解释命名属性属性的操纵和确定。 属性描述符类型的值是由命名字段组成的记录,其中每个字段的名称是属性名称,其值是8.6.1中指定的对应属性值。 另外,任何字段都可以存在或不存在。

另一方面,调用对象方法或键将使用Javascript [[Get]]机制。 那快得多了!

基准

http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array

比较JS中的密钥访问

操作符中使用
 var result = "Impression" in array; 

结果是

var result = array.hasOwnProperty("Impression")
使用hasOwnProperty
var result = array["Impression"] === undefined

结果是

168,270,439 ±0.13 ops/sec     0.02% slower 
直接访问元素(括号样式)
168,303,172 ±0.20%     fastest

结果是

 168,270,439 ±0.13 ops/sec 0.02% slower 
直接访问元素(对象样式)
var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

结果是

 168,303,172 ±0.20% fastest 

编辑:什么是将undefined值分配给属性的原因?

这个问题使我感到困惑。 在Javascript中,至少有两个针对不存在的对象的引用,以避免出现此类问题: nullundefined

null是原始值,表示有意缺少任何对象值,或者简称为已确认的缺少值。 另一方面, undefined是未知值(未定义)。 如果存在稍后将使用适当值的属性,请考虑使用null引用而不是undefined因为在最初的时刻,该属性被确认为缺少值。

相比:

 var a = {1: null}; console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, ie: the value is defined. console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[]. 

劝告

避免使用undefined值的对象。 尽可能直接检查并使用null初始化属性值。 否则,请使用慢速in运算符或hasOwnProperty()方法。

编辑:2018年12月4日-不相关

正如人们所评论的那样,现代版本的Javascript引擎(firefox例外)已经改变了访问属性的方法。 对于这种特殊情况,当前的实现比以前的实现要慢,但是访问密钥和对象之间的差异可以忽略不计。


#6楼

如果您使用的是underscore.js库,则对象/数组操作将变得简单。

在您的情况下,可以使用_.has方法。 例:

yourArray = {age: "10"}

_.has(yourArray, "age")

返回true

但,

_.has(yourArray, "invalidKey")

返回


#7楼

接受的答案Object 。 当心在数组上使用in运算符查找数据而不是键:

("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)

要测试数组中的现有元素: 查找项目是否在JavaScript数组中的最佳方法?


#8楼

这是一个我发现非常有用的辅助函数

这个keyExists(key, search)可以用来轻松地在对象或数组中查找键!

只需将要查找的键传递给它,然后搜索要在其中查找的obj(对象或数组)。

 function keyExists(key, search) { if (!search || (search.constructor !== Array && search.constructor !== Object)) { return false; } for (var i = 0; i < search.length; i++) { if (search[i] === key) { return true; } } return key in search; } // How to use it: // Searching for keys in Arrays console.log(keyExists('apple', ['apple', 'banana', 'orange'])); // true console.log(keyExists('fruit', ['apple', 'banana', 'orange'])); // false // Searching for keys in Objects console.log(keyExists('age', {'name': 'Bill', 'age': 29 })); // true console.log(keyExists('title', {'name': 'Jason', 'age': 29 })); // false 

它已经相当可靠,并且可以跨浏览器很好地工作。


#9楼

回答:

if ("key" in myObj)
{
    console.log("key exists!");
}
else
{
    console.log("key doesn't exist!");
}

说明:

in操作符将检查对象中是否存在键。 如果检查值是否未定义: if (myObj["key"] === 'undefined') ,则可能会遇到问题,因为带有undefined值的键可能存在于对象中。

出于这个原因,更好的做法是先使用in运算符,然后在知道密钥存在后再比较该密钥内部的值。


#10楼

我们可以使用hasOwnProperty.call(obj, key);

underscore.js方法-

if(_.has(this.options, 'login')){
  //key 'login' exists in this.options 
}

_.has = function(obj, key) {
  return hasOwnProperty.call(obj, key);
};

#11楼

香草js

yourObjName.hasOwnProperty(key) : true ? false;

如果要检查对象在es2015中是否至少具有一个属性

Object.keys(yourObjName).length : true ? false

#12楼

ES6解决方案

使用Array#someObject.keys 。 如果给定密钥存在于对象中,则返回true;否则,返回false

 var obj = {foo: 'one', bar: 'two'}; function isKeyInObject(obj, key) { var res = Object.keys(obj).some(v => v == key); console.log(res); } isKeyInObject(obj, 'foo'); isKeyInObject(obj, 'something'); 

单行示例。

 console.log(Object.keys({foo: 'one', bar: 'two'}).some(v => v == 'foo')); 


#13楼

对于那些在项目中包含lodash
有一个lodash的_.get方法,它尝试获取“深”键:

获取对象路径处的值。 如果解析的值未定义,则将在其位置返回defaultValue。

 var object = { 'a': [{ 'b': { 'c': 3 } }] }; console.log( _.get(object, 'a[0].b.c'), // => 3 _.get(object, ['a', '0', 'b', 'c']), // => 3 _.get(object, 'abc'), // => undefined _.get(object, 'abc', 'default') // => 'default' ) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 


这将有效地检查该键(无论深度如何 )是否已定义,并且如果未定义该键,则不会引发可能会损害程序流程的错误。


#14楼

尽管这必须检查键是否存在,但它确实检查值的真实性。 属于哪个undefinednull

Boolean(obj.foo)

此解决方案最适合我,因为我使用打字稿,并'foo' in objobj.hasOwnProperty('foo')使用诸如'foo' in obj类的字符串来检查密钥是否存在,这并不为我提供智能感知。


#15楼

这些示例可以证明不同方法之间的差异。 希望它将帮助您选择适合您的需求的产品:

// Lets create object `a` using create function `A`
function A(){};
A.prototype.onProtDef=2;
A.prototype.onProtUndef=undefined;
var a=new A();
a.ownProp = 3;
a.ownPropUndef = undefined;

// Let's try different methods:

a.onProtDef; // 2
a.onProtUndef; // undefined
a.ownProp; // 3
a.ownPropUndef; // undefined
a.whatEver; // undefined
a.valueOf; // ƒ valueOf() { [native code] }

a.hasOwnProperty('onProtDef'); // false
a.hasOwnProperty('onProtUndef'); // false
a.hasOwnProperty('ownProp'); // true
a.hasOwnProperty('ownPropUndef'); // true
a.hasOwnProperty('whatEver'); // false
a.hasOwnProperty('valueOf'); // false

'onProtDef' in a; // true
'onProtUndef' in a; // true
'ownProp' in a; // true
'ownPropUndef' in a; // true
'whatEver' in a; // false
'valueOf' in a; // true (on the prototype chain - Object.valueOf)

Object.keys(a); // ["ownProp", "ownPropUndef"]

#16楼

全新的JavaScript解构解决方案:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

检查其他使用JavaScript的方法


#17楼

如果要检查对象上任何深度的任何键并考虑虚假值,请考虑将以下行用于实用程序功能:

var keyExistsOn = (o, k) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;

结果

var obj = {
    test: "",
    locals: {
        test: "",
        test2: false,
        test3: NaN,
        test4: 0,
        test5: undefined,
        auth: {
            user: "hw"
        }
    }
}

keyExistsOn(obj, "")
> false
keyExistsOn(obj, "locals.test")
> true
keyExistsOn(obj, "locals.test2")
> true
keyExistsOn(obj, "locals.test3")
> true
keyExistsOn(obj, "locals.test4")
> true
keyExistsOn(obj, "locals.test5")
> true
keyExistsOn(obj, "sdsdf")
false
keyExistsOn(obj, "sdsdf.rtsd")
false
keyExistsOn(obj, "sdsdf.234d")
false
keyExistsOn(obj, "2134.sdsdf.234d")
false
keyExistsOn(obj, "locals")
true
keyExistsOn(obj, "locals.")
false
keyExistsOn(obj, "locals.auth")
true
keyExistsOn(obj, "locals.autht")
false
keyExistsOn(obj, "locals.auth.")
false
keyExistsOn(obj, "locals.auth.user")
true
keyExistsOn(obj, "locals.auth.userr")
false
keyExistsOn(obj, "locals.auth.user.")
false
keyExistsOn(obj, "locals.auth.user")
true

另请参阅以下NPM软件包: https : //www.npmjs.com/package/has-deep-value


#18楼

最简单的检查方法是

"key" in object

例如:

var obj = {
  a: 1,
  b: 2,
}
"a" in obj // true
"c" in obj // false

返回值为true表示键存在于对象中。


#19楼

yourArray.indexOf(yourArrayKeyName)> -1

fruit = ['apple', 'grapes', 'banana']

fruit.indexOf('apple') > -1

真正


fruit = ['apple', 'grapes', 'banana']

fruit.indexOf('apple1') > -1


#20楼

const object1 = {
  a: 'something',
  b: 'something',
  c: 'something'
};

const key = 's';

// Object.keys(object1) will return array of the object keys ['a', 'b', 'c']

Object.keys(object1).indexOf(key) === -1 ? 'the key is not there' : 'yep the key is exist';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值