如何解决字典错误-TypeError:未定义不是对象
我试图在React-Native的JS中以字典/ JSON的形式存储一些数据。
我已经定义了这样的字典:
const [item,setItem] = useState({});
function onUpdate(id,quantity) {
console.debug('tab index : ' + tabIndex);
console.debug('id : ' + id);
console.debug('quantity : ' + quantity);
console.debug(item);
item[tabIndex][id] = quantity;
console.debug(item);
//I'm not setting it
//I have even tried declaring a second object,like :
//let i=item
//It also causes the same problem
}
在日志中,我得到:
[Tue Aug 11 2020 13:19:13.195] DEBUG tab index : 1
[Tue Aug 11 2020 13:19:13.198] DEBUG id : 1
[Tue Aug 11 2020 13:19:13.202] DEBUG quantity : 1
[Tue Aug 11 2020 13:19:13.203] DEBUG {}
[Tue Aug 11 2020 13:19:13.204] ERROR TypeError: undefined is not an object (evaluating 'item[tabIndex][id] = quantity')
那是为什么?
解决方法
如果item
为{}
,则item[tabIndex]
为undefined
;那么item[tabIndex][id]
等效于undefined[id]
,这会导致错误。
理性推理,如@Amaden所述, 由于item [tabIndex]是undefined,因此,当您尝试在该undefined中添加某些内容时,会出现错误。
因此,您应该首先检查未定义的条件,如果是未定义的条件,请先创建对象然后再添加,否则可以直接添加数据。
var item = {};
var tabIndex = 1;
var id = 1;;
if(item[tabIndex] === undefined){
item[tabIndex] = {};
item[tabIndex][id]=10;
} else {
item[tabIndex][id] = 12;
}
console.log(item);
,
item
对象为空{}
,这就是为什么未定义的原因,请检查items
中要设置数据的区域。
首先检查未定义的条件,如果未定义,请先创建对象,然后添加。
if(item[tabIndex] === undefined){
// create object first
} else {
// directly add the data
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。