JavaScript: refactoring avoiding array.push ()

I have a function in an object like this:

arrayofElements: function(item) {

    var result = [];

    if (item.isA) {
        result.push(new Div('aClass', labels['A']));
    }

    if (item.isC) {
        result.push(new Div('cClass', labels['C']));
    }

    if (item.isD) {
        result.push(new Div('dClass', labels['D']));
    }

    return result;
},

How can this be reorganized? I do not like the need () of each element conditionally.

+3
source share
4 answers

You can move properties is*to a sub-object to isolate them, and iterate over the properties of a sub-object

item.is={A:'aClass', C:'cClass'};
...
arrayofElements: function(item) {
    var result = [];
    for (p in item.is) {
        result.push(new Div(item.is[p], labels[p]));
    }
    return result;
},

The values ​​in item.iscan be classes (as shown), or the values ​​in item.iscan be objects with a property class, or you could use the name of the property pas an index in another object to get the classes. This largely depends on what it represents itemand what the element classes are most closely related to.

+4
arrayofElements: function(item) {

var result = [],
    items = ['A', 'C', 'D'];
while(var i=0; i < items.length; i++) {
  if(item["is" + items[i]]) {
    result.push(new Div(items[i] + 'Class', labels[items[i]]))
  }
}
return result;
},

, obj.foo obj ['foo'] Javascript

+1

:

arrayofElements: function(item) {
  var result = [], letters = ['A','C','D'], ltr, i, len;
  len = letters.length;
  for (i = 0; i < len; i++) {
    ltr = letters[i];
    if (item["is"+ltr]) {
      result.push(new Div(ltr.toLowerCase()+"Class", labels[ltr]));
    }
  }
  return result;
},
0

This function avoids the use of push () and is functionally identical to yours:

arrayofElements: function(item) {

    if (item.isA) {
       return [new Div('aClass', labels['A'])];
    }

    if (item.isC) {
       return [new Div('cClass', labels['C'])];
    }

    if (item.isD) {
       return [new Div('dClass', labels['D'])];
    }

    return [];
},
0
source

Source: https://habr.com/ru/post/1730817/


All Articles