I found some answers to similiar questions but I'm still not getting it.
我找到了类似问题的一些答案,但我仍然没有得到它。
but I hope it's a short problem so I dont make too much trouble! ;-)
但我希望这是一个短暂的问题,所以我不会太麻烦! ;-)
I have a js array
我有一个js数组
arr = [ a, b, c]
How can i add value to this elements dynamically? For example I want that each element get the value true
如何动态地为这些元素增加价值?例如,我希望每个元素都获得值true
So it should look like this afterwards:
所以之后看起来应该是这样的:
arr = [ a = true, b = true, c = true];
I tried the following: (using jquery framework)
我尝试了以下内容:(使用jquery框架)
$.each(arr, function(i){
arr[i] = true;
});
but then I just get
但后来我得到了
arr = [ true, true, true]
hope someone can help me! thanx
希望可以有人帮帮我!感谢名单
1 个解决方案
#1
4
arr = [ a = true, b = true, c = true];
That's a different type of data structure you're looking for: not an array, but a mapping. (PHP makes arrays and mappings the same datatype, but that's an unusual quirk.)
这是您正在寻找的不同类型的数据结构:不是数组,而是映射。 (PHP使数组和映射具有相同的数据类型,但这是一个不寻常的怪癖。)
There's not quite a general-purpose mapping in JavaScript, but as long as you're using strings for keys and you take care to avoid some of the built-in JavaScript Object member names, you can use an Object for it:
JavaScript中没有一个通用的映射,但只要您使用字符串作为键并且注意避免使用某些内置的JavaScript Object成员名称,就可以使用Object:
var map= {'a': true, 'b': true, 'c': true};
alert(map['a']); // true
alert(map.a); // true
ETA:
if i have an array how can i make it to look like ["required": true, "checklength": true]?
如果我有一个数组怎么能让它看起来像[“required”:true,“checklength”:true]?
var array= ['required', 'checklength'];
var mapping= {};
for (var i= array.length; i-->0;) {
var key= array[i];
mapping[key]= true;
}
alert(mapping.required); // true
alert('required' in mapping); // also true
alert('potato' in mapping); // false
#1
4
arr = [ a = true, b = true, c = true];
That's a different type of data structure you're looking for: not an array, but a mapping. (PHP makes arrays and mappings the same datatype, but that's an unusual quirk.)
这是您正在寻找的不同类型的数据结构:不是数组,而是映射。 (PHP使数组和映射具有相同的数据类型,但这是一个不寻常的怪癖。)
There's not quite a general-purpose mapping in JavaScript, but as long as you're using strings for keys and you take care to avoid some of the built-in JavaScript Object member names, you can use an Object for it:
JavaScript中没有一个通用的映射,但只要您使用字符串作为键并且注意避免使用某些内置的JavaScript Object成员名称,就可以使用Object:
var map= {'a': true, 'b': true, 'c': true};
alert(map['a']); // true
alert(map.a); // true
ETA:
if i have an array how can i make it to look like ["required": true, "checklength": true]?
如果我有一个数组怎么能让它看起来像[“required”:true,“checklength”:true]?
var array= ['required', 'checklength'];
var mapping= {};
for (var i= array.length; i-->0;) {
var key= array[i];
mapping[key]= true;
}
alert(mapping.required); // true
alert('required' in mapping); // also true
alert('potato' in mapping); // false