使用.join()无法正常连接嵌套在数组内对象中的数组

时间:2016-06-29 22:10:01

标签: javascript arrays object join

我正在接收一个文件,解析它,将信息存储在一个对象中并将该对象推送到一个数组。该对象的一个​​值是'sequence':[]名称值对。一旦我将DNA序列存储到我对象中'sequence'的值中,我想加入所有元素。但是,我尝试使用.join()无效。以下是我的代码:

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // Great success! All the File APIs are supported.
} else {
  alert('The File APIs are not fully supported in this browser.');
}

var objArray = [];
var obj;

function parse(event) {
//Get the file from HTML input tag
var file = event.target.files[0];

if(file) {

    //Create a new file reader
    var reader = new FileReader();
    //When the file reader loads
    reader.onload = function(evt) {
        //Add the contents of file to variable contents
        var contentsByLine = evt.target.result.split('\n'); 
        //Alert user the file upload has succeeded
        console.log('File ' + file.name + ' was successfully loaded.');

        for(var i in contentsByLine){
            if(contentsByLine[i][0] == '>'){
                obj = {
                    id: contentsByLine[i],
                    sequence: [],
                    lead_trim: 0,
                    trail_trim: 0
                };
                objArray.push(obj);
            }else{
                obj.sequence.push(contentsByLine[i]);
            }
           // console.log(objArray[i]['sequence']);
        }
        console.log(objArray)

        // Create the DataView.
        var dataView = new Slick.Data.DataView();

        // Pass it as a data provider to SlickGrid.
        var grid = new Slick.Grid("#table", dataView, columns, options);

        // Make the grid respond to DataView change events.
        dataView.onRowCountChanged.subscribe(function (e, args) {
          grid.updateRowCount();
          grid.render();
        });

        dataView.onRowsChanged.subscribe(function (e, args) {
          grid.invalidateRows(args.rows);
          grid.render();
        });

        var data = [];

        for (var i in objArray){
            objArray[i]['sequence'].join();
            data.push(objArray[i]);
        }

        dataView.setItems(data);
        dataView.getItems();
        //console.log(data);
    }
    reader.readAsText(file);
} else {
    alert('Failed to upload file!');
}

}

document.getElementById('fileItem').addEventListener('change', parse, false);

2 个答案:

答案 0 :(得分:0)

您需要将结果存储在变量中,例如:

var result = objArray[i]['sequence'].join();
data.push(result);

更短的:

data.push( objArray[i]['sequence'].join() );

答案 1 :(得分:0)

您使用的连接不正确。 Join返回一个值。你需要将它设置为某种东西。

for (var i in objArray){
    objArray[i]['sequence'].join();
    data.push(objArray[i]);
}

应改为:

for (var i = 0; i < objArray.length; i++){
    objArray[i]['sequenceString'] = objArray[i]['sequence'].join();
    data.push(objArray[i]);
}