2017-06-21 4 views
0

私は周りにグーグルでグーグルを作る方法について完全に混乱しています。& JSで連想配列(私は実際にはオブジェクトであることがわかります)を操作します。私はこのように私のページの要素をIループとして連想配列/オブジェクトを構築しようとしている:ループを介して関連配列を作成する方法(および別の配列を使用してコンテンツを取得する方法)

var array_modules = {}; 
$('.module').each(function() { 
    var this_element = $(this); 
    var module_top = this_element.data('top'); 
    var module_bottom = this_element.data('bottom'); 
    array_modules.push({'top': module_top, 'bottom': module_bottom}); 
}); 

そしてどこかに私はこのように私のアレイのコンテンツを取得したいと思います:

for (var index in array_modules) { 
    var top = array_modules['top']; 
    var bottom = array_modules['bottom']; 
    alert('top = ' + top + ' and bottom = ' + bottom); 
} 

しかしこれのどれもうまくいかない。私は間違って何をしていますか?コードのあなたの最初の部分で

答えて

1

は、あなたはちょうどあなたが連想配列を反復している第二部ではarray_modules = [];を使用しますが、それはarray_modules[index]['top']をする必要があり、ちょうど配列と連想ないようarray_modulesを使用しています。それでも、配列に変更するだけで、ループはforEachになります。

とにかく、これは私がどうなるのかです:

var array_modules = []; 

$('.module').each(function() { 
    array_modules.push($(this).data()); 
}); 

array_modules.forEach(function(data){ 
    console.log(data.top, data.bottom); 
}) 
2

あなただけの配列にデータをプッシュすることができます。以下のコードがあなたに役立つことを願っています。

var array_modules = []; 
$('.module').each(function() { 
    var this_element = $(this); 
    var module_top = this_element.data('top'); 
    var module_bottom = this_element.data('bottom'); 
    array_modules.push({'top': module_top, 'bottom': module_bottom}); 
}); 
for (var index in array_modules) { 
    var top = array_modules[index]['top']; 
    var bottom = array_modules[index]['bottom']; 
    alert('top = ' + top + ' and bottom = ' + bottom); 
} 

これは連想オブジェクトの配列

+0

おかげで、正しい答えを作成しますが、私は彼が公正であることを検証しなければならなかった以前のそれを@juvian与えた。.. – drake035

+0

はクール!お力になれて、嬉しいです –

関連する問題