1

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

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

1 Answer 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.)

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
Sign up to request clarification or add additional context in comments.

3 Comments

For the benefit of the OP and other novices, please note that using this method, there is no length property as you are accustomed to with normal, indexed arrays. Also, iteration over this data type must be done using for..in (w3schools.com/jS/js_loop_for_in.asp), as opposed to an array which should be iterated over using the standard for structure (w3schools.com/jS/js_loop_for.asp).
hey. thank you but i still dont know how to add an value to a element as i descriped above. u just show me how to set up a object with value direct ..but if i have an array (or object... ) so ["required", "checklength"] (firebug) how can i make it to look like ["required": true, "checklength": true]? maybe my english isnt good enough to descripe it clearly! :-(
An array in JS with named keys is an object. He answered your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.