在JavaScript中的函数内部声明变量

时间:2018-07-23 15:26:02

标签: javascript

因此,当我在函数内声明变量时,我会遇到这个问题,它告诉我声明了该变量,但从未读取过它的值,当我再次尝试使用此变量时,它是未定义的,并且尝试了不同的文本编辑器,同样的问题 the functions that i want the variable to be define in

enter image description here

the error that came out

2 个答案:

答案 0 :(得分:0)

如前所述,警告开发人员使用该变量还需要做更多的工作。它不会停止执行代码。

但是,绝对需要注意,以下是消除此错误的可能选项:

1)从pickedColor函数返回随机值

var colors = {
  "length": 200
};

function pickedColor() {
  return Math.floor(Math.random() * colors.length);
}

function generateRandomColors(nums) {
  var arr = [];
  for (var i = 0; i < nums; i++) {
    arr.push(pickedColor());
  }
  return arr;
}
console.log(generateRandomColors(8));

2)增加随机变量的范围

var colors = {
  "length": 200
};
var random = 0;

function pickedColor() {
  random = Math.floor(Math.random() * colors.length);
}

function generateRandomColors(nums) {
  var arr = [];
  for (var i = 0; i < nums; i++) {
    pickedColor()
    arr.push(random);
  }
  return arr;
}
console.log(generateRandomColors(8));

答案 1 :(得分:0)

发生警告是因为您没有返回来自 pickedColor()的任何内容。您创建了 random 变量,但未返回。因此,当您尝试使用该功能时,您会得到 undefined 。可以通过在 pickedColor()函数中添加返回值来解决此问题:

function pickedColor(){
  return Math.floor(Math.random() * colors.length);
}
相关问题