简体   繁体   English

在具有连接名称的对象中添加元素

[英]add element in object with concatenate name

I have object $scope.form . 我有对象$scope.form I want to add various elements in it as $scope.form.elem1, $scope.form.elem2, $scope.form.elem3 and so on. 我想在其中添加各种元素,例如$scope.form.elem1, $scope.form.elem2, $scope.form.elem3等。

I tried some ways but nothing worked for me. 我尝试了一些方法,但没有任何效果。

for(i = 0; i <= addr.length; i++) {
  $scope.form.elem = addr.i; //What should be here ??
}
$scope.form["text"+variable] = addr[i];

Use brackets [] when you want to access a property with either a variable value, concatenated string or string with abnormal characters like "." 如果要访问带有变量值,串联字符串或带有异常字符(如“”)的字符串的属性,请使用方括号[] .

Assume you have the values in array addr . 假设您在数组addr具有值。
You can iterate the object properties with a string like this. 您可以使用这样的字符串迭代对象属性。

for (let i = 0; i < addr.length; i++) {
   $scope.form['yourName' + i] = addr[i];
}

Are you looking like this : 你看起来像这样:

var noOfelements = 100; // you can have your addr array also 
var key;
for(i = 1; i <= noOfelements; i++) {
 key = "elem"+i;
 $scope.form[key] = i; //i is just for reference you can give value to each element as per your need
}

below is the output you will get the same output with $scope also. 下面是输出,您将也获得与$ scope相同的输出。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM