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

前端 未结 4 1807
时光取名叫无心
时光取名叫无心 2021-01-28 05:47

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 ar

相关标签:
4条回答
  • 2021-01-28 06:45

    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.

    0 讨论(0)
  • 2021-01-28 06:50

    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"]
    
    0 讨论(0)
  • 2021-01-28 06:50

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

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

    Good Luck!!!

    0 讨论(0)
  • 2021-01-28 06:53

    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?

    0 讨论(0)
提交回复
热议问题