【问题标题】:Alternate ways of applying method to array将方法应用于数组的替代方法
【发布时间】:2015-12-31 22:40:35
【问题描述】:

我正在为编码训练营准备课前材料。所以,我在寻找指导,而不是答案。我不知道如何解决这个问题。有一个 HTML 文件可以检查答案的每一步。使用我目前编写的代码(如下),我不断收到此响应——“预期 {} 有一个属性 'push'”和 'pop' 的相同错误。我相信我添加的方法不正确。但是除了使用原型之外,我找不到任何其他方法来添加方法,原型将方法应用于所有 Array 对象。我也试过做简单的测试,但也失败了。

// returns an empty array object. this object should have the following    methods:
// push(val) adds val to the end of the array
// pop() removes a value from the end and returns it
// the goal of this problem is to reverse engineer what array methods are actually doing and return an object that has those methods
function createArray() {
    //CODE HERE
    var array = [];
    array.push = function(val){ 
        array[array.length] = val;
        return array;   
    };
    array.pop = function(){
        return array[array.length-1];
    };

}
createArray();
console.log(array.push(hey));

以及错误信息:

console.log(array.push(hey));
            ^
ReferenceError: array is not defined
    at Object.<anonymous> (/Users/Fox/Documents/Programming/Codesmith/precourse-part-1/Level-2-Intermediate/src/main.js:67:13)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

我意识到数组是一个局部变量。但是一旦我调用函数 createArray 不应该是全局的吗?任何指导将不胜感激。

我是编码新手。请温柔一点。

【问题讨论】:

  • 您的变量 array 是函数 createArray 的本地变量 - 因此您无法在 console.log 调用中的函数之外访问它。

标签: javascript arrays methods scope


【解决方案1】:

您在函数内部声明数组,因此它是函数范围的。它将无法从该函数外部访问。您可以做的是从函数返回数组并将结果分配给变量。

 function createArray() {
    var array = [];
    array.push = function(val){ 
        array[array.length] = val;
        return array;   
    };
    array.pop = function(){
        return array[array.length-1];
    };

    return array;
}

var myArray = createArray();
console.log(myArray.push('hey')); // ["hey"]

演示:http://jsfiddle.net/6Lo5Laon/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2020-06-15
    • 2012-02-11
    相关资源
    最近更新 更多