简体   繁体   English

Javascript跨浏览器foreach

[英]Javascript cross browser foreach

I am trying to write a cross browser foreach method/function. 我正在尝试为foreach方法/功能编写一个跨浏览器。 It should be possible to either use the real, or a copy of the values or properties of the array or object to iterate over (just like the PHP foreach ($array as &$item) ). 应该可以使用实数或数组或对象的值或属性的副本进行迭代(就像PHP foreach ($array as &$item) )。

Neither the forEach nor the map method is cross browser compatible, so I will be needing for loops. forEach和map方法都不与跨浏览器兼容,因此我将需要循环。

This topic JavaScript for...in vs for warned me to not use for... in to loop through arrays, but when I test with the following code: 本主题的JavaScript for ... in与for提醒我不要使用for... in遍历数组,但是当我使用以下代码进行测试时:

var arr = [];
arr[3] = "foo";
arr[0] = "bar";
arr["baz"] = "baz";

for (var i in arr) {
    alert(i);
}

I get the results 3, 0 and baz (which is correct). 我得到结果3、0和baz(正确)。 This also seems to work on indexed arrays (0, 1, 2). 这似乎也适用于索引数组(0、1、2)。 Yet Object.prototype.toString.call(arr) === "[object Array]" returns true. 然而Object.prototype.toString.call(arr) === "[object Array]"返回true。

So what is the best cross browser approach to create a foreach method which will iterate over both array values and object properties, ideally offering the option to work with the actual values/properties of the array/object? 那么,最好的跨浏览器方法是创建一个foreach方法,该方法将遍历数组值和对象属性,理想情况下提供使用数组/对象的实际值/属性的选项?

Just check the hasOwnProperty when using for..in that'll resolve most danger issue: 只需在使用for..in hasOwnProperty时检查hasOwnProperty ,即可解决大多数危险问题:

for (var name in buz) {
    if (buz.hasOwnProperty(name)) {
        // do stuff
    }
}
var arr = [];
arr[3] = "foo";
arr[0] = "bar";
arr["baz"] = "baz";

for (var i in arr) {
    alert(arr[i]);
}

Cheers! 干杯!

You may be interested in a utility library like underscore.js . 您可能对underscore.js之类的实用程序库感兴趣。 It provides many useful utility functions like each and map . 它提供了许多有用的实用程序功能,例如eachmap If available, it uses the native implementation, otherwise it falls back to its own custom implementation. 如果可用,它将使用本机实现,否则将退回到其自己的自定义实现。 The library is also relatively small at 4kb for the production version. 对于生产版本,该库也相对较小,为4kb。

If, however, you are really motivated to do this on your own, then the underscore.js source at the very least could illuminate exactly how this is done. 但是,如果您真的有动力自行执行此操作,那么underscore.js源代码至少可以准确说明此操作的完成方式。 Their each is near the top. 他们每个人都靠近顶部。 The line starts with 'var each = _.each = ...' 该行以“ var each = _.each = ...”开头

You could rest assured the code is high quality as it's likely to have been scrutinized and optimized multiple times. 您可以放心,代码可能是经过多次审查和优化的高质量代码。

This should work for array and object, the attribute checks are not necessary, they are just there for demonstration purposes. 这应该适用于数组和对象,属性检查不是必需的,它们只是用于演示目的。

function forEach(object, callBack) {
    var tObject = Object.prototype.toString.call(object),
        i,
        l;

    if (tObject !== "[object Array]" && tObject !== "[object Object]") {
        throw new TypeError("'object' must be an array or object");
    }

    if (Object.prototype.toString.call(callBack) !== "[object Function]") {
        throw new TypeError("'callBack' must be a function");
    }

    if (tObject === "[object Array]") {
        i = 0;
        l = object.length;

        while (i < l) {
            callBack(object[i], i);

            i += 1;
        }

        return;
    }

    for (i in object) {
        if (object.hasOwnProperty(i)) {
            callBack(object[i], i);
        }
    }

    return;
}

var test1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
var test2 = {
    "a": 10,
    "b": 11,
    "c": 12,
    "d": 13,
    "e": 14,
    "f": 15,
    "g": 16,
    "h": 17,
    "i": 18
};

forEach(test1, function (element, index) {
    console.log(index, element);
});

forEach(test2, function (element, index) {
    console.log(index, element);
});

On jsfiddle jsfiddle上

I've also setup a performance test for you to have a look at on jsperf 我还为您设置了性能测试,以了解jsperf

for (var i in arr) {
    if (arr.hasOwnProperty(i)) {
        alert(i + '--->' + arr[i]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM