0

So I have this array:

[first_name: false, last_name: false, email: false, month: false, day: false, year: false, password: false, password2: false]

Now I if I do this console.log(arrayName.length) it will return 0; why? What I'm doing wrong?

//LE

This is how I do it:

var errors = {};
 $('.register-front').delegate('button','click',function(){
  var $this = $(this).parent().parent().parent();
  $this.find('input,select').each(function(){
    if(!$(this).val() || ($(this).val() == '-1'))
    {
      errors[$(this).attr('name')] = false;
    }
  });
  console.log(errors.length);
  return false;
 });

I made some changes but I still don't get it....

4
  • 2
    That's the structure of an object, not an array. Commented Nov 11, 2012 at 16:08
  • There are no associative arrays in JS. You should use an object (map) instead. Commented Nov 11, 2012 at 16:10
  • Use var errors = {}; to initialize your associative array (a.k.a. "plain object" in JavaScript lingo). Commented Nov 11, 2012 at 16:12
  • See my updated answer. You can use Object.keys(errors).length instead of errors.length. Commented Nov 11, 2012 at 16:28

3 Answers 3

8

Your notation seems odd. The square brackets are for an array, but the contents are object attribute/value notation. I don't think that will work. You can turn your expression into an object by replacing the [] with {}, but then, objects don't have length. You can get the number of keys in an object with:

Object.keys(obj).length

Alternatively, you can iterate through the object keys with:

for (var key in obj) {
    . . .
}

EDIT For the specific code you added, you can replace this line:

console.log(errors.length);

with:

console.log(Object.keys(errors).length);
Sign up to request clarification or add additional context in comments.

Comments

0

In JavaScript, assotiative-array-like structure is Object:

{
    lorem: 'ipsum',
    dolor: 'amet'
}

In your example, replace square brackets with curly brackets, and you'll get such object.

Comments

0

That isn't an Array, an Array is a simple list of values where as this is a mapping of keys to values, i.e. an Object. You mean to do something like:

var myObject = { first_name: false, last_name: false, email: false, month: false, day: false, year: false, password: false, password2: false }

Comments

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.