How could I manipulate this array in Javascript for this kind of error checking?

做~自己de王妃 提交于 2019-12-20 07:24:05

问题


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 with two commas in a row separating an element instead of one comma .. Not just comma , any other wrong input.

var cars=["Saab",,"Volvo","BMW"]; // Here , this array has an error , there's a double comma .
var cars=["Saab",*"Volvo","BMW"]; // this array has an error , there's an asterix.
var cars=["Saab","Volvo","BMW"];  // this array is the right one.

Here's the wrong array

What Javascript function or solution could I use to make sure an array is checked and no error is within it .. Only elements and separating commas with no space in between.

Your help would be so much appreciated.


回答1:


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.




回答2:


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.

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"]



回答3:


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

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

Good Luck!!!




回答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?



来源:https://stackoverflow.com/questions/15621232/how-could-i-manipulate-this-array-in-javascript-for-this-kind-of-error-checking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!