2014-02-21 2 views
0

Мне было интересно, есть ли у меня правильный синтаксис. Я хочу, чтобы функция умножала возврат двух других функций, а затем делила результат. Я включил сценарий ниже. Проверьте третью функцию calculateSquareFeet. Я имею в виду var theSquareFeet.Функция, которая умножает возврат других функций, затем делит на 144

//Set up an associative array 
//The keys represent the size of the plants 
//The values represent the square inches required per plant 
var square_inches = new Array(); 
square_inches ["seeds"]=16; 
square_inches ["seedlings"]=16; 
square_inches ["juveniles"]=64; 
square_inches ["adult"]=144; 


//Set up an associative array 
//The keys represent the number of plants 
//The value represents the the number 
//We use this this array when the user selects a number from the forms first select box 
var num_plant= new Array(); 
    num_plant ["none"] = 0; 
    num_plant [1] = 1; 
    num_plant [2] = 2; 
    num_plant [3] = 3; 
    num_plant [4] = 4; 
    num_plant [5] = 5; 
    num_plant [6] = 6; 
    num_plant [7] = 7; 
    num_plant [8] = 8; 
    num_plant [9] = 9; 
    num_plant [10] = 10; 
    num_plant [11] = 11; 
    num_plant [12] = 12; 
    num_plant [13] = 13; 
    num_plant [14] = 14; 
    num_plant [15] = 15; 
    num_plant [16] = 16; 
    num_plant [17] = 17; 
    num_plant [18] = 18; 
    num_plant [19] = 19; 
    num_plant [20] = 20; 
    num_plant [21] = 21; 
    num_plant [22] = 22; 
    num_plant [23] = 23; 
    num_plant [24] = 24; 
    num_plant [25] = 25; 

var type_grow = new Array(); 
    type_grow [select] =0; 
    type_grow [trad] =15; 
    type_grow [hydro] =21; 
    type_grow [undec] =0; 



//This function finds the number of plants based on the 
//drop down selection 
function getNumberOfPlants() 
{ 
    var userNumberChoice=0; 
    //Get a reference to the form id="sqfoot" 
    var theForm = document.forms["sqfoot"]; 
    //Get a reference to the select id="plantNumber" 
    var selectedPlantNum = theForm.elements["plantNumber"]; 

    //set userNumberChoice equal to value user chose 
    //For example num_plant[5.value] would be equal to 5 
    userNumberChoice = num_plant[selectedPlantNum.value]; 

    //finally we return userNumberChoice 
    return userNumberChoice; 
} 




// This function finds a number that represents square inches 
// Here, we need to take user's the selection from radio button selection 
function getSquareInches() 
{ 
    var thePlantSize=0; 
    //Get a reference to the form id="sqfoot" 
    var theForm = document.forms["sqfoot"]; 
    //Get a reference to the plant size the user Chooses name=selectedPlant": 
    var selectedPlant = theForm.elements["plantType"]; 
    //Here since there are 4 radio buttons selectedPlant.length = 4 
    //We loop through each radio buttons 
    for(var i = 0; i < selectedPlant.length; i++) 
    { 
     //if the radio button is checked 
     if(selectedPlant[i].checked) 
     { 
      //we set thePlantSize to the value of the selected radio button 
      //i.e. if the user choose Juvenile we set it to 32 
      //by using the square_inches array 
      //We get the selected Items value 
      //For example square_inches["Juvenile".value]" 
      thePlantSize = square_inches[selectedPlant[i].value]; 
      //If we get a match then we break out of this loop 
      //No reason to continue if we get a match 
      break; 
     } 
    } 
    //We return thePlantSize 
    return thePlantSize; 
} 

function calculateSquareFeet() 
{ 
    /* Here we get the square feet by multiplying getNumberOfPlants() x getSquareInches() then divide by 144, the square inches in a square foot */ 
    var theSquareFeet = (getNumberOfPlants() * getSquareInches())/144; 

     return theSquareFeet; 
} 
+0

так что не так? .. его совершенно нормально –

+2

Вы * действительно * должны рассмотреть возможность использования цикла для создания 'num_plant'. – meagar

+0

@Pilot - Посмотрите на код. Слишком много, чтобы указать в моих 550 символах. Он даже не будет разбираться из-за удаленных ключей в type_grow. Код в настоящее время представляет собой кучу спагетти, для которой требуется 30 минут, прежде чем кто-нибудь даже начнет отвечать на вопрос. –

ответ

0

Синтаксис третьей функции верен.

хотя бы уменьшить его:

function calculateSquareFeet(){ 
    return getNumberOfPlants() * getSquareInches()/144; 
} 

Но это не делает то, что вы написали неправильно. theSquareFeet не требуется. Технически он отбрасывает немного барана и несколько циклов процессора. Но это не так.

+0

Спасибо за обмен. – Learn2Earn

+0

Да, это отвечает на мой вопрос. И совет о сокращении кода был оценен. – Learn2Earn

+0

Если бы я знал, как это сделать. – Learn2Earn

0

Вы уже сделали правильную функцию, которую вы хотите, однако, насколько синтаксиса вы сделали ошибку построения type_grow массива

Оно должно быть:

var type_grow = new Array(); 
    type_grow ["select"] =0; 
    type_grow ["trad"] =15; 
    type_grow ["hydro"] =21; 
    type_grow ["undec"] =0; 

Для дальнейшего чтения на ассоциативных массивах в javascript, этот сайт имеет хорошее объяснение: http://www.i-programmer.info/programming/javascript/1441-javascript-data-structures-the-associative-array.html

+1

@MatthewBlancarte зайдите в jsfiddle или w3schools и протестируйте его, вы, безусловно, можете присвоить эти значения этим клавишам – Tim

+0

Возможно, я должен был сказать, что вы не должны назначать эти ключи массиву. Вы больше не используете 'Array' в качестве массива в строгом смысле. Вы по существу используете его как объект. Конечно, он работает, но попытайтесь получить длину этого «ассоциативного массива», и вы обнаружите, что оно равно 0, хотя у вас есть четыре элемента. –

+1

Правильный javascript способ присвоить ассоциативный массив - он не сработает с 'невозможно установить свойство неопределенного ', если вы не инициализируете его с помощью' new Array() 'или' [] 'first.OP уже использовал некоторые в своем коде, поэтому должен знать, как ссылаться на элементы внутри (как и с массивом 'square_inches'.) – Tim

Смежные вопросы