我希望将数组存储在Javscript函数中,以便在初始化后调用时检索存储的值。
我试过这个:
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不是一个函数
发布于 2021-08-23 12:27:53
我不知道这是不是你想要达到的目标,但它是有效的:
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 ]发布于 2021-08-23 12:47:22
如果您不想使用class,您总是回到prototype方法,在那里创建一个构造函数(注意:class只是这个原型方法的语法糖,从长远来看可能更容易理解)。
// 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]));
发布于 2021-08-23 12:30:20
这是因为myFunc.init无效;myFunc是一个函数,而不是一个对象。
你可以试试这个:
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.https://stackoverflow.com/questions/68892579
复制相似问题