关于遍历数组

function each(item, fn) {
    if (Array.prototype.forEach) {
        // 若支持forEach方法
        item.forEach(fn)
    } else {
        // 不支持forEach的时候 便遍历并执行
        for (var i in item) {
            fn(i, item[i])
            console.log(i);
        }
    }
}
var arr = ['java', 'c', 'php', 'html']
function output(item, index) {
    console.log(item);
    console.log(index + ': ' + item)
}
each(arr, output)

这里的output即为fn的实参,而fn 中i 和item[i]分别为第一参数和第二参数,不应该是对应

output里面的item 和index 吗?但是如果是这样,output里面的item 和index 不应该调换

位置吗?最终调试是上面代码是正确的,但是实在想不通,求助

阅读 3.1k
4 个回答

clipboard.png
js中数组的foreach方法,第一个参数是遍历的元素,第二个是索引,第三个是数组本身.

clipboard.png

箭头所指的这里,你的写法是有问题的,和js中数组foreach方法参数不同.
应该改为

for (var i in item) {
    fn(item[i], i);   // 第一个是遍历的元素,第二个参数是索引
    console.log(i);
  }

另外,js中的数组,不推荐使用for...in遍历,具体百度
另外,jquery的each方法,第一个是索引,第二个参数是遍历的元素,你是不是把jquery和js的foreach参数给搞混了?

楼上无趣写的很好
其实要兼容forEach可以直接抄个polyfill啊 然后就可以愉快的arr.forEach(output)了
polyfill如下摘抄自mozilla

forEach 是在第五版本里被添加到 ECMA-262 标准的;这样它可能在标准的其他实现中不存在,你可以在你调用 forEach 之前 插入下面的代码,在本地不支持的情况下使用 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 = thisArg;
    }

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

你这个方法应该走的是forEach存在的情况,而不是第二种情况。

。。是因为你的浏览器支持foreach
下图是使用for in的输出

clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题