我想打印我的答案到控制台

时间:2014-08-02 09:00:11

标签: javascript

我对编程非常陌生。我按照codeacademy.com上的教程进行了操作,并且我坚持了几个教程。它给我带来了console.log()

的麻烦

第一个是一个简单的函数,计算5个橙子的成本,每个5美元。

var orangeCost = function(price){
    var cost = price * 5;  //the 5 is the number of oranges

};

orangeCost(5); 

并且教程说这是正确的。但是,我想将答案返回到控制台,当我尝试

console.log(orangeCost(5));

我收到错误说" TypeError:字符串不是函数"。

另一个给我同样错误的是

var my_number = 7; //this has global scope

var timesTwo = function(number) {
    var my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
}; 

timesTwo(7);

console.log("Outside the function my_number is: ");
console.log(my_number);

2 个答案:

答案 0 :(得分:2)

只需这样做 -

return cost;

orangecost -

var orangeCost = function(price){
    var cost = price * 5;  //the 5 is the number of oranges
    return cost;
};

console.log(orangeCost(5)); 

答案 1 :(得分:0)

当您执行类似下面的操作

时,会出现"TypeError: string is not a function"错误
console.log("orangeCost"(5));// so here "orangeCost" is a string you cann't use that as function.

你必须从你的功能中回来。

var orangeCost = function(price){
    var cost = price * 5;  //the 5 is the number of oranges
    return cost
};