使用 javascript 遍历值列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14777030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate over a list of values using javascript
提问by user990951
I am looking to iterate over a list of values using javascript.
我正在寻找使用 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.
我的目标是根据标签将每一行传递给不同的函数。我想弄清楚多维数组是否是最好的方法。
回答by driangle
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);
}
}
You get to define the matchesLabelfunction, it should return true if the item needs to be passed to your function.
您可以定义matchesLabel函数,如果需要将项目传递给您的函数,它应该返回 true。
回答by Tomas Petovsky
If you would like to make it more pro, you can use this function
如果你想让它更专业,你可以使用这个功能
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);
}
This function allows you to run it in context you want (typical scenario is windowcontext) and pass some arguments. Hope this helps ;)
这个函数允许你在你想要的上下文中运行它(典型的场景是窗口上下文)并传递一些参数。希望这可以帮助 ;)

