js adding a value to a element in an array
I found some answers开发者_C百科 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
arr = [ a, b, c]
How can i add value to this elements dynamically? For example I want that each element get the value true
So it should look like this afterwards:
arr = [ a = true, b = true, c = true];
I tried the following: (using jquery framework)
$.each(arr, function(i){
arr[i] = true;
});
but then I just get
arr = [ true, true, true]
hope someone can help me! thanx
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.)
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:
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]?
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
精彩评论