findIndex() method issue with internet explorer

独自空忆成欢 提交于 2019-11-30 08:00:30

问题


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?


回答1:


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;
        }
    }
    



回答2:


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

how to use:

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



回答3:


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;}); 



回答4:


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]
);



回答5:


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]
);


来源:https://stackoverflow.com/questions/37698996/findindex-method-issue-with-internet-explorer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!