将方法应用于数组

时间:2015-10-04 00:29:14

标签: javascript arrays methods scope

我正在为编码训练营开设课前材料。所以,我正在寻找指导,而不是答案。我对如何处理这个问题感到茫然。有一个HTML文件可以检查答案的每个步骤。根据我目前编写的代码(下方),我不断收到此回复 - "期望{}有一个属性'推送'" ' 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它不应该是全局的吗?任何指导都将不胜感激。

我是编码的新手。请温柔。

1 个答案:

答案 0 :(得分: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"]

DEMO:http://jsfiddle.net/6Lo5Laon/

相关问题