javascript - hasOwnProperty 的意外行为
问题描述
我正在编写一个函数来检查对象是否包含像“id”或“serif:id”这样的键。不幸的是,这不能正常工作。
function returnIdPreferSerifId(object) {
if (object.hasOwnProperty('serif:id' === true)) {
return object['serif:id'];
} else if (object.hasOwnProperty('id' === true)) {
return object.id;
} else {
console.log(object)
console.log(object.hasOwnProperty('serif:id' === true))
console.log(object.hasOwnProperty('id' === true))
throw `ID not found in Layer 1!`;
}
}
测试对象为:
{
id: 'ska',
d: 'M255.848,145.321l19.839,0.054l12.677,8.62l6.085,-8.62l-8.62,-29.41l-30.488,13.637l0.507,15.719Z',
style: 'fill:rgb(187,222,251);stroke:white;stroke-width:1.33px;'
}
我希望该函数返回“ska”,因为它是对象 ID。相反,控制台显示
false
false
path\to\module\modules\svgHandler.js:135
throw `ID not found in Layer 1!`;
^
ID not found in Layer 1!
提前感谢您的帮助!
解决方案
你的括号放错地方了:
if (object.hasOwnProperty('serif:id' === true))
应该
if (object.hasOwnProperty('serif:id') === true)
如果你愿意,你可以放弃 === true
if (object.hasOwnProperty('serif:id'))
推荐阅读
- sql - System.Data.OleDb.OleDbException:“标准表达式中的数据类型不匹配。” 网格视图更新
- postgresql - 是否可以将 EXECUTE 语句嵌套为 PostgreSQL 中的源记录集?
- hadoop - ambari REST API + 如何从 ambari 获取所有版本
- javascript - 加载以前的结果并防止页面跳转
- python - 广度优先搜索未返回节点的正确排序
- reactjs - 反应选择删除边框和框阴影
- tfs - 我可以在“工作项树”类型的 TFS 查询中隐藏没有孩子的父母吗?
- react-native - 使用 Jest 进行 React-Native FlatList RenderItem 测试
- php - 在这种情况下如何在单括号中输入 PHP 变量
- postgresql - postgresql 中的压缩归档日志