9

I am looking to iterate over a list of values using javascript.

I have a list like this

Label: A    Value:  Test    Count: 4
Label: B    Value:  Test2   Count: 2
Label: C    Value:  Test3   Count: 4
Label: D    Value:  Test4   Count: 1
Label: C    Value:  Test5   Count: 1

My goal is to pass each row into different functions based on the label. I am trying to figure out if a multidimensional array is the best way to go.

4

3 に答える 3

17
var list = [
   {"Label": "A", "value": "Test", "Count": 4},
   {"Label": "B", "value": "Test2", "Count": 2},
   {"Label": "C", "value": "Test3", "Count": 4},
   {"Label": "D", "value": "Test4", "Count": 1},
   {"Label": "C", "value": "Test5", "Count": 1}
]

for(var i = 0, size = list.length; i < size ; i++){
   var item = list[i];
   if(matchesLabel(item)){
      someFunction(item);
   } 
}

関数を定義することができmatchesLabelます。アイテムを関数に渡す必要がある場合は、trueを返す必要があります。

于 2013-02-08T16:31:10.150 に答える
2

もっとプロにしたい場合は、この機能を使用できます

function exec(functionName, context, args )
{
    var namespaces = functionName.split(".");
    var func = namespaces.pop();

    for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }

    return context[func].apply(this, args);
}

この関数を使用すると、必要なコンテキスト (典型的なシナリオはウィンドウコンテキスト) で実行し、いくつかの引数を渡すことができます。お役に立てれば ;)

于 2013-02-08T16:44:20.467 に答える