Home  >  Article  >  Web Front-end  >  Summary of methods for returning multiple values ​​in JS methods_javascript tips

Summary of methods for returning multiple values ​​in JS methods_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:58:191413browse

When programming with JS, sometimes it is necessary to return two or more data in one method. This can be achieved by using the following methods:

1 The way to use arrays is as follows:

<html>
<head>
  <title>JS函数返回多个值</title>
</head>
<body>
  <input type="button" onclick="getNames()" value="test" />

  <script type="text/javascript">
function getData()
{
  var names=new Array("oec2003","oec2004");
  return names;
}
function getNames()
{
  var names=getData();
  alert(getData()[0]); //返回oec2003
}
</script>

</body>
</html>
 

2 Encapsulate the data into Json and return it, as follows:

<html>
<head>
<title>JS函数返回多个值</title>
</head>
<body>
<input type="button" onclick="getInfo()" value="test"/>
<script type="text/javascript">
function getData()
{
  var info={"name":"oec2003","age":"25"};
  return info;
}
function getInfo()
{
  var info=getData();
  var name=info["name"];
  var age=info["age"];
  alert("姓名:"+name+" 年龄:"+age);
}
</script>
</body>
</html>

For a more detailed introduction to Json, please see here

3 This is the simplest method, look at the code below:

<html>
<head>
<title>JS函数返回多个值</title>
</head>
<body>
<input type="button" onclick="getInfo()" value="test"/>
<script type="text/javascript">
  function getData()
  {
    return ["oec2003", 25]
  }
  function getInfo()
  {
    var info = getData();
    alert("姓名:" + info[0] + "年龄:" + info[1]);
  }
</script>
</body>
</html>

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn