foreach的替代方案,并使用常规循环

时间:2018-04-16 19:40:52

标签: javascript

这在IE中确实不起作用

[].forEach.call(document.querySelectorAll('.some-class-selector'), function(arg) {

   callSomeFucntion(arg)

});

因为forEach不适用于IE。如果我想用for循环来做这个,我该怎么做?

2 个答案:

答案 0 :(得分:0)

需要在IE中运行forEach

ServerValue.TIMESTAMP

答案 1 :(得分:-1)

您使用的是哪个版本的IE? forEach的Microsoft文档页面列出了不支持它的版本 - 主要是IE 6,7和8或怪癖模式(https://docs.microsoft.com/en-us/scripting/javascript/reference/foreach-method-array-javascript

如果您的浏览器不支持,我们也可以使用polyfill MDN forEach

  

forEach()被添加到第5版的ECMA-262标准中;如   这样它可能不存在于标准的其他实现中。   您可以通过在以下位置插入以下代码来解决此问题   脚本的开头,允许使用forEach()   不能原生支持它的实现。这个算法是   正好是ECMA-262第5版中指定的那个,假设为Object   和TypeError有它们的原始值和那个callback.call()   计算为Function.prototype.call()的原始值。

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {

Array.prototype.forEach = function(callback/*, thisArg*/) {

var T, k;

if (this == null) {
  throw new TypeError('this is null or not defined');
}

// 1. Let O be the result of calling toObject() passing the
// |this| value as the argument.
var O = Object(this);

// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;

// 4. If isCallable(callback) is false, throw a TypeError exception. 
// See: http://es5.github.com/#x9.11
if (typeof callback !== 'function') {
  throw new TypeError(callback + ' is not a function');
}

// 5. If thisArg was supplied, let T be thisArg; else let
// T be undefined.
if (arguments.length > 1) {
  T = arguments[1];
}

// 6. Let k be 0.
k = 0;

// 7. Repeat while k < len.
while (k < len) {

  var kValue;

  // a. Let Pk be ToString(k).
  //    This is implicit for LHS operands of the in operator.
  // b. Let kPresent be the result of calling the HasProperty
  //    internal method of O with argument Pk.
  //    This step can be combined with c.
  // c. If kPresent is true, then
  if (k in O) {

    // i. Let kValue be the result of calling the Get internal
    // method of O with argument Pk.
    kValue = O[k];

    // ii. Call the Call internal method of callback with T as
    // the this value and argument list containing kValue, k, and O.
    callback.call(T, kValue, k, O);
  }
  // d. Increase k by 1.
  k++;
}
// 8. return undefined.
};
}
相关问题