首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >函数初始化以在调用时检索存储的值。

函数初始化以在调用时检索存储的值。
EN

Stack Overflow用户
提问于 2021-08-23 12:18:36
回答 3查看 46关注 0票数 0

我希望将数组存储在Javscript函数中,以便在初始化后调用时检索存储的值。

我试过这个:

代码语言:javascript
运行
复制
function myFunc() {
  this.myArr = [];

  function init() {
    if (myArr.lenght === 0) {
      myArr.push(1);
      myArr.push(2);
      myArr.push(3);
      console.log("initialized now");
    } else {
      console.log("initialized already. Arrlength: ", myArr.lenght);
    }
  }

  return myArr;
}

myFunc.init()

console.log(myFunc());

预期产出:

现在初始化

已经初始化了。长度:3

获得的产出:

TypeError: myFunc.init不是一个函数

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-08-23 12:27:53

我不知道这是不是你想要达到的目标,但它是有效的:

代码语言:javascript
运行
复制
function myFunc() {
  myArr = [];
  function init() {
    if (myArr.length === 0) {
      myArr.push(1);
      myArr.push(2);
      myArr.push(3);
      console.log("initialized now");
    } else {
      console.log("initialized already. Arrlength: ", myArr.length);
    }
  }
  
  function getArr() {
    return myArr;
  }
  
  myFunc.init = init;
  myFunc.getArr = getArr;
}

myFunc();
myFunc.init();
console.log(myFunc.getArr()); // output: Array(3) [ 1, 2, 3 ]
票数 1
EN

Stack Overflow用户

发布于 2021-08-23 12:47:22

如果您不想使用class,您总是回到prototype方法,在那里创建一个构造函数(注意:class只是这个原型方法的语法糖,从长远来看可能更容易理解)。

代码语言:javascript
运行
复制
// Constructor. Set the array to null
function Example() {
  this.arr = null;
}

// `init` can accept an array argument
// If there is an array, set `this.arr` to it
// otherwise use the default array
Example.prototype.init = function(arr) {
  if (arr && arr.length) {
    this.arr = arr;
    return `Initialized now. length: ${this.arr.length}`;
  } else {
    this.arr = [1, 2, 3];
    return `Initialized already. length: ${this.arr.length}`;
  }
}

// Not passing in an array so we use
// the default array
const instance = new Example();
console.log(instance.init());

// Passing in an array that gets assigned
const instance2 = new Example();
console.log(instance2.init([1]));

票数 3
EN

Stack Overflow用户

发布于 2021-08-23 12:30:20

这是因为myFunc.init无效;myFunc是一个函数,而不是一个对象。

你可以试试这个:

代码语言:javascript
运行
复制
class Something {
    constructor() {
        this.myArr = [1];
    }

    init() {
        if (this.myArr.length === 0) {
            this.myArr.push(1);
            this.myArr.push(2);
            this.myArr.push(3);
            console.log("initialized now");
        } else {
            console.log("initialized already. Arrlength: ", this.myArr.length);
        }
    }
}

new Something().init() // would give desired results.
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68892579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档