如何检查值是否是JavaScript中的对象?
当前回答
如果typeof yourVariable==“object”,则它是一个对象或null。
如果要排除null、数组或函数,只需执行以下操作:
if (
typeof yourVariable === 'object' &&
!Array.isArray(yourVariable) &&
yourVariable !== null
) {
executeSomeCode();
}
其他回答
我有一段代码片段可以使用。当没有给出整段代码时,我觉得很困惑,所以我自己创建了它:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunc()">Try it</button>
<script>
var abc = new Number();
// var abc = 4;
//this is a code variation which will give a diff alert
function myFunc()
{
if(abc && typeof abc === "object")
alert('abc is an object and does not return null value');
else
alert('abc is not an object');
}
</script>
</body>
</html>
如果明确希望检查给定值是否为{}。
function isObject (value) {
return value && typeof value === 'object' && value.constructor === Object;
}
这很棘手,因为数组是对象类型,函数是对象类型而实际对象{}也是对象类型
问题
const arr = []
const fun = function(){}
const actualObj = {}
arr instanceof Object // true
fun instanceof Object // true
actualObj instanceof Object // true
因此目标是actualObj必须返回true,其他所有值都必须返回false
actualObj instanceof Object && !(actualObj instanceof Array) && !(typeof actualObj === 'function') // true
function isObjectLike(value) {
return value != null && typeof value == 'object' && !Array.isArray(value);
}
基于lodash
有点晚了。。。对于“普通对象”(我的意思是,像{'x':5,'y':7}),我有一个小片段:
function isPlainObject(o) {
return (o === null || Array.isArray(o) || typeof o == 'function' || o.constructor === Date ) ?
false
:(typeof o == 'object');
}
它生成下一个输出:
console.debug(isPlainObject(isPlainObject)); //function, false
console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true
console.debug(isPlainObject(5)); //number, false
console.debug(isPlainObject(undefined)); //undefined, false
console.debug(isPlainObject(null)); //null, false
console.debug(isPlainObject('a')); //string, false
console.debug(isPlainObject([])); //array?, false
console.debug(isPlainObject(true)); //bool, false
console.debug(isPlainObject(false)); //bool, false
它总是适用于我。只有当“o”的类型是“object”,但没有null、数组或函数时,If才会返回“true”。:)
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔