我正在尝试将一个项目推送到数组,但它不起作用。当我运行代码时,我收到此错误:
--未捕获的类型错误:data.allItems[type].push 不是函数--
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};
return {
addItem: function(type, des, val) {
var newItem, ID;
// Create new ID
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
// Create new item based on 'inc' or 'exp' type
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
// Push it into our data structure
data.allItems[type].push(newItem);
// Return the new element
return newItem;
},
您需要首先检查对象中是否存在所需的数组。如果是这样,那就推动它。
if(data.allItems[type] && Array.isArray(data.allItems[type])) {
data.allItems[type].push(newItem);
} else {
console.warn(type + " is undefined in `allItems`!");
}
// OR
if (data.allItems[type] == undefined || !Array.isArray(data.allItems[type])) {
// Your Error handler
}
注意:您只能执行push()
and pop()
数组上的方法。
const finalArray = {};
finalArray.push({ id: 1}) // You will definitely get an error.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)