【问题标题】:Undefined is not an function data[index].pushundefined 不是函数 data[index].push
【发布时间】: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


【解决方案1】:
 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 {
                       data[index] = {
                            name: csh.val().color,
                            population: data[index].population + 1,
                            color: csh.val().color.toLowerCase(),
                            legendFontColor: '#7F7F7F',
                            legendFontSize: 15
                        }
                }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 2016-11-08
    • 2019-12-11
    • 2021-05-17
    • 2020-10-12
    • 2015-10-29
    • 2015-06-05
    • 2019-10-16
    相关资源
    最近更新 更多