2016-03-29 69 views
0

我有一個驗證表單輸入的函數,我需要返回驗證的值。現在,我使用if else子句調用個別驗證器,所以我的函數僅返回第一個驗證字段(age),但我想將agelastNamefirstName返回給調用函數。如何從JavaScript函數返回多個值

如何獲取多個要返回的值?

validationForm(numberOfPassengers){ 
    for (let i=0; i < numberOfPassengers; i++) { 
     let firstName = ReactDOM.findDOMNode(this.refs['firstName'+typeOfPassenger+i]).value; 
     let lastName = ReactDOM.findDOMNode(this.refs["lastName"+typeOfPassenger+i]).value 
     let age = ReactDOM.findDOMNode(this.refs['age'+typeOfPassenger+i]).value; 
     let regex = /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/; 
     let resultFirstName = firstName.match(regex); 
     let resultLastName = firstName.match(regex); 
     if(age <= 0){ 
     ('.age-alignment').addClass('error-border'); 
     }else{ 
     return age; 
     }; 
     if(resultFirstName){ 
     return firstName; 
     }else{ 
     ('.first-name').addClass('error-border'); 
     }; 
     if(resultLastName){ 
     return lastName; 
     }else{ 
     ('.last-name').addClass('error-border'); 
     }; 
    } 
    } 
+0

如果您使用React,則不要手動操作DOM。 – dandavis

+0

可以請你詳細說明 –

回答

0

JavaScript沒有從函數返回多個對象的概念。相反,您必須構建一個包含以下值的對象:

var returnObject = {}; 
    if(age <= 0){ 
    ('.age-alignment').addClass('error-border'); 
    }else{ 
    returnObject.age = age; 
    }; 
    if(resultFirstName){ 
    returnObject.firstName = firstName; 
    }else{ 
    ('.first-name').addClass('error-border'); 
    }; 
    if(resultLastName){ 
    returnObject.lastName = lastName; 
    }else{ 
    ('.last-name').addClass('error-border'); 
    }; 
    return returnObject; 
0

我試圖簡化邏輯。如果不需要,也沒有理由添加else語句。另外,看看我如何用你想要作爲參數傳遞的變量調用第二個函數。

function other_function(age,last_name, first_name){ 
     console.log("I have access to all of these:",age,last_name,first_name) 
    } 

validationForm(numberOfPassengers){ 
    for (let i=0; i < numberOfPassengers; i++) { 
     let firstName = ReactDOM.findDOMNode(this.refs['firstName'+typeOfPassenger+i]).value; 
     let lastName = ReactDOM.findDOMNode(this.refs["lastName"+typeOfPassenger+i]).value 
     let age = ReactDOM.findDOMNode(this.refs['age'+typeOfPassenger+i]).value; 
     let regex = /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/; 
     let resultFirstName = firstName.match(regex); 
     let resultLastName = firstName.match(regex); 
     if(age <= 0){ 
     ('.age-alignment').addClass('error-border'); 
     } 
     if(!resultFirstName){ 
     ('.first-name').addClass('error-border'); 
     }; 
     if(!resultLastName){ 
     ('.last-name').addClass('error-border'); 
     } 
     return other_function(age,first_name,last_name) 
    } 
    }