everyone!

I have an array containing some strings:

我有一个包含一些字符串的数组:

strs = ['a1','a2','a3']

and an object is defined:

并定义了一个对象:

o={}

I wanna add properties to o while the property name is the string in array strs Any suggestion is appreciated

我想添加属性为o而属性名称是数组中的字符串strs任何建议表示赞赏

2 个解决方案

#1


4

Try the following

请尝试以下方法

for (var i = 0; i < strs.length; i++) {
  var name = strs[i];
  o[name] = i;
}

This code will create the properties with the given name on the object o. After the loop runs you will be able to access them like so

此代码将在对象o上创建具有给定名称的属性。循环运行后,您将能够像这样访问它们

var sum = o.a1 + o.a2 + o.a3;  // sum = 3

Here's a fiddle which has some sample code

这是一个小提琴,有一些示例代码

  • http://jsfiddle.net/eYJrJ/

更多相关文章

  1. JavaScript String(字符串对象)
  2. JS将字符串转换为数组
  3. 创建一个对外界只读的属性,但是我的方法仍然可以设置
  4. 可编辑div中的文本计数和子字符串
  5. Javascript没有返回样式属性[重复]
  6. 使用append方法将对象转换为字符串
  7. javascript小技巧&&JavaScript[对象.属性]集锦 [转载了多篇]
  8. 将子属性添加到jsdoc中的现有属性列表
  9. AngularJS:TypeError:无法读取未定义的属性'get'?

随机推荐

  1. PostreSQL崩溃试验全记录
  2. 基于Sqlcipher和GreenDao的数据库加密
  3. MySQL延迟关联性能优化方法
  4. Maven + Struts2 + JasperReport + MSSQL
  5. 有没有办法在SQL中将每个值作为一行返回
  6. 如何将图像加载到PictureBox;基于存储在D
  7. MySQL字段名与保留字冲突
  8. sqlserver2008r2查找非中文字母数字出现
  9. 如果有相同的记录,我增加数值,如果没有,则插
  10. vs2010下vc调用sqlite3数据库以及配置