开发者

Javascript "forEach" loop question

I saw somewhere the code snippet:

list.forEach(callback, this);

I understand 'forEach' loop except 'this' keyword used here, what does 'this' mean?

if I convert list.forEach(callback) to 开发者_如何学Cnormal for loop, I think it is:

for(var n=0; n<list.length; n++){
   callback(list[n]);
}

But what does 'this' means in forEach(callback, this) ? With this, what need to be added if I convert it to normal for loop like above?


this is used as the this object when executing callback.

 for(var n=0; n<list.length; n++){
       callback.call(this, list[n]);
    }

see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach


this is the current object. The method list.forEach() would be called within object context. You should be able to use the snippet by passing the object you want to loop as the second argument, example:

var obj = {
    a: "foo",
    b: "bar"
}

list.forEach(callback, obj);


The forEach is not standard javascript, but probably was part of a library. The Dojo Toolkit has a forEach construct like that, or it could have been a method added to the Array() prototype.

The this argument was most likely an identifier of which object should have context for the callback function. That is, if the callback function itself calls this, which object outside the callback function it should refer to.


There is a forEach on arrays that takes a function which takes a single value which is applied to each element in the collection. A practical example of using a forEach loop is the following which parses the url parameters of the web page:

var query = location.search.slice(1);    
var result = {}, keyValuePairs = query.split('&');

keyValuePairs.forEach(function(keyValuePair) {
    keyValuePair = keyValuePair.split('=');
    result[keyValuePair[0]] = keyValuePair[1] || '';
});

You can then use the result object as an associative array or map like structure and get values out of it with var somevalue = result["somekey"]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜