简体   繁体   中英

findIndex() method issue with internet explorer

I am doing some tests with differents browsers using the Selenium::Remote::Driver module.

I would like to check if I find some item in my web site list, list from a framework JavaScript (which creates grids). For this case I have to use JavaScript snippet allowed by Selenium::Remote::Driver .

I wrote the following code

$script = q{

      var paramProgramName = arguments[0];

      var list  = $('#c-list').dxList('instance');
      var items = list.option('items');
      var index = items.findIndex(function(el){ return el.name == paramProgramName; });

      list.selectItem(index);

      return ;
};

$driver->execute_script($script, $programName);

It works fine with Chrome and Firefox but not with Internet Explorer because the findIndex method is only supported by version 12 and following. For some reason I have to use version 11.

What can I do differently to get an index from every browser?

So my question is how can i do differently to get my index for every browser ?

You have at least three options:

  1. Shim Array#findIndex ; MDN has a shim/polyfill you can use.

  2. Use something else that IE11 has, such as Array#some (which even IE9 has):

     var index = -1; items.some(function(el, i) { if (el.name == paramProgramName) { index = i; return true; } }); 
  3. Use something else that even IE8 has, such as for :

     var index = -1; for (var i = 0; i < items.length; ++i) { if (items[i].name == paramProgramName) { index = i; break; } } 

you can use http://underscorejs.org/ ,

how to use:

var index = _.findIndex(objects, function(item){
return item.name == programName;
});

A better way:

var findArrayIndex = function (array, predicateFunction) {
    var length = array == null ? 0 : array.length;
    if (!length) {
        return -1;
    }
    var index = -1;
    for (var i = 0; i < array.length; ++i) {
        if(predicateFunction(array[i])) {
            index = i;
            break;
        }
    }
    return index;
}

Usage:

findArrayIndex(cachedAnnouncementsArray, function(o){return o.ID == 17;}); 

Another way:

var objects = [
  { 'key' : 1, 'name' : 'ABC' },
  { 'key' : 2, 'name' : 'QLP' },
  { 'key' : 3, 'name' : 'XYZ' },
];

function filterByKey(obj) {
  if ('key' in obj) {
    return obj.key === 'some_value';
  }
}

var index = objects.indexOf(
  objects.filter(filterByKey)[0]
);

Instead of:

const index = items.findIndex(el => el.name == paramProgramName);

You can achieve the same result in two IE9 operations like so:

const index = items.indexOf(
    items.filter(el => el.name == paramProgramName)[0]
);

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