简体   繁体   中英

JavaScript: Subsititute ForEach and callback in anonymous function

function to_json(workbook) {
  var result = {};

  workbook.SheetNames.forEach(function(sheetName) {
    var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
    if(roa.length > 0){
      result[sheetName] = roa;
    }
  });
  return result;
}

I have above code. How to alter it, in order to let the anonymous function run only over the first element in SheetNames? (or alternatively alter sth else in order to achieve the same result).

I got this so far, I am not sure it is correct.

...snip

var tmpArray = workbook.SheetNames.slice(0);

  tmpArray.forEach(function(sheetName) {

...snip

One way is what you've mentioned, but .slice(0) returns the whole array, so use .slice(0,1) for only the first item:

var tmpArray = workbook.SheetNames.slice(0, 1);
tmpArray.forEach(function(sheetName) { /* ... */ })

But if you only want to process the first item you can cancel the forEach() and the anonymous() totally:

function to_json(workbook) {
    var result = {},
        sheetName = workbook.SheetNames[0],
        roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
    if(roa.length > 0) result[sheetName] = roa;
    return result;
}

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