【发布时间】:2019-05-16 09:27:30
【问题描述】:
我有一个数组叫做:
const data = []
我创建了一个函数,在该函数中循环 true 数组以检查名称是否已存在。
let index = data.findIndex(x => x.name == csh.val().color);
console.log(index); <-- gives me the right index back
console.log(data);
console.log(data[index].population); <-- this gives me the right value back
if (index === -1) {
data.push({
name: csh.val().color,
population: csh.val().color ? 1 : 1,
color: csh.val().color.toLowerCase(),
legendFontColor: '#7F7F7F',
legendFontSize: 15
});
}else {
if(data && data[index]) {
data[index].push({
name: csh.val().color,
population: data[index].population + 1,
color: csh.val().color.toLowerCase(),
legendFontColor: '#7F7F7F',
legendFontSize: 15
})
}
}
但是我在 else 语句中得到一个错误: undefined is not an function on this line:
data[index].push({
更新:
这是数组的样子:
const data = [
{ name: "brown", population: 5, color: 'brown', legendFontColor: '#7F7F7F', legendFontSize: 15 },
{ name: "red", population: 5, color: 'brown', legendFontColor: '#7F7F7F', legendFontSize: 15 },
]
【问题讨论】:
-
对象,不是数组?
-
我有一个包含对象的数组。我会更新它,让你看看它的样子。
-
by
data[index].push()你试图推入对象 - 使用data.push()
标签: arrays reactjs react-native indexing undefined