学习Javascript但坚持使用简单的return关键字

时间:2014-12-12 09:30:32

标签: javascript

我正在学习Javascript,所以请善待。我有以下代码,无法理解有什么问题,但我不需要直接回答,而是了解问题是什么:

// Parameter is a number, and we do math with that parameter
var timesTwo = function(number) {
    return number * 2;
};

// Call timesTwo here!
var newNumber = function(timesTwo){
    print(newNumber);
};

timesTwo(4);

我正在关注Code academy的教程。

3 个答案:

答案 0 :(得分:1)

var timesTwo = function(number) {
    return number * 2;
};

// Call timesTwo here!
var newNumber = function(number){
    console.log(timesTwo(number));
};

newNumber(4);

尝试这个..

答案 1 :(得分:0)

通过思考它来计算它:我意识到我的语法不正确。

// Parameter is a number, and we do math with that parameter
var timesTwo = function(number) {
    return number * 2;
};

// Call timesTwo here!
var newNumber = timesTwo(2);
    console.log(newNumber);

以上作品。

答案 2 :(得分:0)

这里有你的代码

// here you define a function named 'timesTwo' which receive a number as parameter, so 'TimesTwo' is a function, in Javascript, function is also a type , can be assigned to variable, so here you assign function to variable 'timesTwo'
var timesTwo = function(number) {
    return number * 2;
};

// Here you defined another function called newNumber and passed a function as parameter, first of all, the parameter timesTwo is never used in this fuction,
// secondly, you are trying to print a variable newNumber which is not defined in the scope of this function, remember, javascript has function scope
var newNumber = function(timesTwo){
    print(newNumber);
};

// you finally called 'timesTwo' function with parameter 4 , which return value 8, but this is no statement to print it out, that's why you don't get it print on screen
timesTwo(4)

要使其按预期工作,请使用上面的@Alok代码

参考文献:

Javascript scope and context

Javascript function