javascript - Why does data is not defined appear after return data?
过去多啦不再A梦
过去多啦不再A梦 2017-05-19 10:41:05
0
5
861
function getData() {
    var data = new Array();
  for (var i=0; i<list.length; i++) {
    var city_text = list[i].firstChild.nodeValue;
    var city = city_text.substring(0,2);    //截取字符串,从0到2,但不包括2.
    var num = list[i].lastChild.innerHTML;
    data[i] = [city,num];
    }
  alert(data.length);    //7
  return data;
}
alert(data.length);    //data is not defined

Already return data, why can’t the external data be called?

过去多啦不再A梦
过去多啦不再A梦

reply all(5)
仅有的幸福

The data you are talking about is a local variable defined in the getData method and cannot be used outside. You can use a variable to accept the return value
var myData =getData()

大家讲道理

You need to get the value with getData before you can use it.

洪涛

The function getData was just defined before, but not called;
If called, a variable needs to be used to receive the return value, such as:
var datas = getData();

data is a local variable in the function and cannot be accessed outside the function. The external access is actually the data variable defined externally. If it is not defined externally, it will prompt not defined;
The list used in the getData function is not defined in the function, so it should be defined outside the function. It is best to change it to a function parameter:
function getData(list){

...

}
Call:
var datas = getData(list);

In addition, when there is an external list variable, the parameter of getData is also a list. The parameter list is used inside the function, not the external variable list.
In order to distinguish, you can change the parameters to different ones, such as:
function getData(listParam){

... // 函数内部使用listParam代替list

}
The call remains unchanged:
var datas = getData(list);
The parameter used when calling is the external variable list. When executing, list is assigned to listParam, and listParam is used inside the function to represent the parameters passed to the function

我想大声告诉你

Because your data is declared with var inside the function, it is a local variable of the function and cannot be called directly outside the function. Although you can return the data data through > return, but you call it outside the function. When using a function, you have to set a variable to accept the return value

洪涛

...this question.

It should be written like this outside the function: alert(getDtata().length). As for why, let’s clarify the basics first.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template