简体   繁体   中英

Undefined error in reading the property of object

Please help to solve the undefined error coming in my console while running the below code

Please see this JSbin also http://jsbin.com/ONOwujA/1/edit

data = [
    {key:"home",value:"hk1"},
    {key:"home",value:"hk2"},
    {key:"home",value:"hk3"},
    {key:"home",value:"hk4"},
    {key:"product",value:"pk1"},
    {key:"product",value:"pk2"},
    {key:"product",value:"pk3"},
    {key:"product",value:"pk4"},
    {key:"service",value:"sk1"},
    {key:"service",value:"sk2"},
    {key:"service",value:"sk3"},
    {key:"service",value:"sk4"}
];

myFilteredKey=[];
for(i=0;i<=data.length;i++){

    if(myFilteredKey.indexOf(data[i].key)!=-1){
        myFilteredKey.push(data[i].key);
        console.log(data[i].key);
    }
}

Use i < data.length . If the length is 3 , the maximum index is 2 .

Another problem with your code is that no element will be added to myFilteredKey . Since the array is already empty, no element will satisfy the condition myFilteredKey.indexOf(data[i].key)!=-1 . Maybe you want to use === -1 instead, ie check whether the element is not in the array rather than whether it's in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM