分配给新值时保留对象属性

时间:2017-06-28 09:23:10

标签: javascript javascript-objects

我有一个这样的对象:

serviceSpec = {

   jsonData:{
       attachments: []
   }

};

function createJson(value){
    serviceSpec.JsonData = {sample: value}; //Line 1
    serviceSpec.jsonData.attachments.push('check'); //Line 2
}

createJson('test');

问题是serviceSpec.jsonData.attachments.push('check')引发错误,说第2行未定义serviceSpec.jsonData.attachments

显然,在第1行,serviceSpec.JsonData被分配给新值,但是如何保留我在上面定义的对象结构(附件)?

2 个答案:

答案 0 :(得分:3)

只需向Object添加属性,而不是重新定义它:

FileInputStream excelFile;
Workbook workbook;
try {
    excelFile = new FileInputStream(new File(fileName));
    workbook = new XSSFWorkbook(excelFile);

    Sheet datatypeSheet = workbook.getSheetAt(0);
    for (Row currentRow : datatypeSheet) {
        for (Cell cell : currentRow) {
            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                System.out.print(cell.getStringCellValue() + "||");
            } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                System.out.print(cell.getNumericCellValue() + "||");
            }
        }
        System.out.println();
    }
} catch (IOException e) {
    e.printStackTrace();
}

答案 1 :(得分:2)

使用Object.assign:

chcp 65001
:call mkdir("привет")