jQuery 使用 $.each 遍历对象 [英] jQuery iterate over object with $.each

查看:23
本文介绍了jQuery 使用 $.each 遍历对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象 options: options = {title : 'title1', name : 'name1', url : 'url1', etc.}

作为函数的参数传入.我正在尝试遍历该对象,将其传递给另一个函数 evaluate,并将结果存储在另一个对象 opts 中,如下所示:

which is passed in as a parameter to a function. I'm trying to iterate over that object, pass it through another function evaluate, and store the result in another object opts, like so:

var opts = new Object();

$.each(options, function(key,value){
opts.key = evaluate(element, value);
});

evaluate(element,value) 工作正常,但问题是 opts 最终看起来像:

The evaluate(element,value) works fine, but the problem is that opts ends up looking like:

{key : eval(element,url1)}

而不是

{title : eval(element,title1), name : eval(element,name1), etc.}

也就是说,key 是按字面意思传递而不是被求值,并被每次迭代用 options 中的最后一个属性覆盖.

That is, key gets passed literally instead of being evaluated, and gets overwritten with each iteration with the last property in options.

我的作业行中的语法是否正确?我也试过了:

Do I have the right syntax in my assignment line? I also tried:

opts = {key : eval(element,val)}

它给出了与上面相同的结果.我还可以在 $.each 迭代中将对象转换为数组.我已经尝试了几种方法来做到这一点,也没有成功.如果有人能告诉我那条路线,那就太好了.

which gave the same result as above. I can also convert the object to an array within the $.each iteration. I've tried several ways of doing that, also unsuccessfully. If someone can show me that route, that would be great too.

(这是一个 jQuery 插件,我正在 Firefox 中使用 Firebug 进行测试).

(This is for a jQuery plugin, and I'm testing using Firebug in Firefox).

提前感谢您的帮助.

推荐答案

你已经发现这是文字键'key':

As you've discovered this is the literal key 'key':

opts.key = evaluate(element, value);

要使用动态键,请使用 []:

To use a dynamic key use []:

opts[key] = evaluate(element, value);

具体例子:

var o = {};
o["test"] = "foo";
alert(o.test);

这篇关于jQuery 使用 $.each 遍历对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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