Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 15:58:19
Original
1440 people have browsed it

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>
 

Copy after login

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>
Copy after login

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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template