Javascript jQuery数组。内部映射。每个

Javascript jQuery数组。内部映射。每个,javascript,jquery,arrays,map,each,Javascript,Jquery,Arrays,Map,Each,我在$中有一个数组。每个函数。我想遍历它来创建一个新的或修改过的数组。但是我需要从外部访问$(this)。每个循环: // target these data attributes: $selector = $('[data-my0], [data-my1], [data-my2]'); $.each($selector, function() { var $this = $(this), // cache selector keys = ['my0'

我在
$中有一个数组。每个
函数。我想遍历它来创建一个新的或修改过的数组。但是我需要从外部访问
$(this)
。每个
循环:

// target these data attributes:
$selector = $('[data-my0], [data-my1], [data-my2]');

$.each($selector, function() {        

    var $this = $(this), // cache selector
        keys = ['my0', 'my1', 'my2']; // array of data keys

    // I want to use the keys array to make a vals array to this:
    // var vals = [$this.data('my0'), $this.data('my1'), $this.data('my2')];

    // This doesn't seem to work (can't read from length 0 error):
    var vals = $.map( keys, function( key ) { return $this.data(key); });

}); 
我认为使用
$可以做到这一点。每个
$。映射
,但这就是我被卡住的地方。我知道
$(此)
通常不与
$一起使用。map
$一样。每个
。在本例中,我试图从外部传递表示选择器的
$this

等待-您正在将“VAL”传递到“$.map()”cal中,而不是“keys”:


这是一个jsfiddle。代码运行得很好,但如果看不到实际的HTML,就很难准确地知道您希望发生什么。

这不是问题的一部分,但您可以编写
$selector。每个(…)
也可以。您有一个带有
的类型我认为。@pimvdb是的,这也是一个问题,但不会导致“无法从长度0读取”错误。我没有从代码中得到那个错误。@pimvdb谢谢(这就是我必须在5:30醒来开车送我妈妈去机场时发生的事情LOL)。这是好是坏b/c,这意味着这可以工作,但我肯定在其他地方有问题。谢谢:)html就像
——在小提琴中也是这样工作的。又是Thx。
var vals = $.map( keys, function( key ) { return $this.data(key); });