错误:未捕获的TypeError:无法读取未定义的属性“值”

时间:2015-11-19 07:27:08

标签: javascript arrays

var myData = '[["absa",1447842600000,1492],["amer",1447842600000,8698],["apac",1447842600000,8361],["emea",1447842540000,70406],["odc",1447842660000,0]]';

$(document).ready(function () {
    var myData = new Array();
    for (i in myData) {
        var item = myData[i];
        var key = item[0];
        var value = [item[1], item[2]];
        var index = getElementindex(key);
        if (index != -1) {
            var element = finalArr[index];
            element.value.push(value);
        } else {
            var newArr = new Array();
            var element = {
                key: "",
                value: ""
            };
            element.key = key;
            newArr.push(value);
            element.value = newArr;
            finalArr.push(element);
        }
    }

    function getElementindex(key) {
        for (i in finalArr) {
            if (finalArr[i].key == key) return -i;
        }
        console.log(JSON.stringify(finalArr));
    }
});

3 个答案:

答案 0 :(得分:2)

时会覆盖myData字符串的值
var myData = new Array();

要将字符串转换为JSON对象,请使用

myData = JSON.parse(myData);

答案 1 :(得分:0)

试试这个,eval()将字符串解析为JS中的实际数组

$(document).ready(function() {
    var myData = new Array();
    myDataString = '[["absa",1447842600000,1492],["amer",1447842600000,8698],["apac",1447842600000,8361],["emea",1447842540000,70406],["odc",1447842660000,0]]';
    myData = eval(myDataString);
    // code goes here

答案 2 :(得分:0)

<script>
var mstdta=[['A',453627726262,10],['A',453627726262,5],['B',453627726262,10],['B',453627726262,0],['C',453627726262,10],['C',453627726262,70]];

$(document).ready(function() {

    var myArray = new Array();

    for(i in mstdta){
        var item=mstdta[i];
        var key=item[0];
        var value=[item[1],item[2]];
        var index=getElementIndex(key);
        if(index!=-1){
            var element=myArray[index];
            element.value.push(value);

        }else{
            var newArr=new Array();
            var element={key:"",value:""};
            element.key=key;
            newArr.push(value);
            element.value=newArr;
            myArray.push(element);
        }
    }

    function getElementIndex(key){
        for(j in myArray){
            if(myArray[j].key==key)
                return j;
        }
        return -1;
    }
    console.log(JSON.stringify(myArray));


}); 
</script>