在变量名是字符串时声明变量?
16lz
2021-01-22
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/
更多相关文章
- JavaScript String(字符串对象)
- JS将字符串转换为数组
- 创建一个对外界只读的属性,但是我的方法仍然可以设置
- 可编辑div中的文本计数和子字符串
- Javascript没有返回样式属性[重复]
- 使用append方法将对象转换为字符串
- javascript小技巧&&JavaScript[对象.属性]集锦 [转载了多篇]
- 将子属性添加到jsdoc中的现有属性列表
- AngularJS:TypeError:无法读取未定义的属性'get'?