Skip to content Skip to sidebar Skip to footer

How Could I Manipulate This Array In Javascript For This Kind Of Error Checking?

How can I make Javascript check an array and make sure that there's no error committed after the comma separating each element of the array .. For example a user may form an array

Solution 1:

Given that you are trying to validate user-entered data, I'd suggest reevaluating your approach.

You should not require end-users to enter data in valid JavaScript syntax; this is annoying to your users.

Instead, I'd just have a textarea and instructions.

mockup

This is far easier for humans to deal with, and parsing is super simple:

var cars = document.getElementById('carstextarea').value.split('\n');
// => ["Saab","Volvo","BMW"]

Solution 2:

Use a static code analyzer such as JSLint or JSHint.

The latter is available as a JavaScript library in addition to the web-hosted flavor.

Solution 3:

You can use jslint takes a JavaScript source and scans it ,

visual studio, netbeans or eclipse have a plugin for that.

Good Luck!!!

Solution 4:

Your second cars example with the * in it won't compile.

To check for double commas, you can iterate over the array and check for an undefined value.

for(var i = 0; i<cars.length; i++) {
if(cars[i] === undefined) {
// do something
}
}

Alternatively you could try and catch this before you generate the array. Is there a way to check for an empty row inputted by the user?

Post a Comment for "How Could I Manipulate This Array In Javascript For This Kind Of Error Checking?"