_.each(list,iterator,[context])中的上下文是什么? [英] What is context in _.each(list, iterator, [context])?

查看:92
本文介绍了_.each(list,iterator,[context])中的上下文是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是underscore.js的新手。 _。each()中的 [context] 的用途是什么?它应该如何使用?

解决方案

context参数设置这个值

  var someOtherArray = [name,patrick,d,w ]; 

_each([1,2,3],function(num){
//在这里,this指向与someOtherArray相同的数组

alert(this [num]); // num是被迭代的数组的值
//所以这个[num]获得
//的num索引处的项目someOtherArray。
},someOtherArray);

工作示例 http://jsfiddle.net/a6Rx4/



它使用数组中每个成员的数字迭代获得 someOtherArray 索引的项目,该项目由 this 表示,因为我们将其作为上下文传递给它如果你没有设置上下文,那么这个会引用参数。窗口对象。


I am new to underscore.js. What is the purpose of [context] in _.each()? How should it be used?

解决方案

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

这篇关于_.each(list,iterator,[context])中的上下文是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆