整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

前端基础 - Javascript函数传值的方式

文首发在个人博客上:http://www.brandhuang.com/article/1587859232291

函数传值

《JavaScript高级程序设计》书中说:ECMAScript中所有函数的参数都是按值传递的。

按值传递

把函数外部的值复制给函数内部的参数,就和把值从一个变量复制到另一个变量一样。

基本数据类型

传递的是原始值本身

在函数中修改传入的值,不会影响原来的数据

var value = 1;
function foo(v) {
    v = 2;
    console.log(v); //2
}
foo(value);
console.log(value) // 1

复杂数据类型

传递的是对象的引用的副本,看下面两个例子,看看有什么不一样?

// 例子1
var obj = {
    value: 1
};
function foo(o) {
    o.value = 2;
    console.log(o.value); //2
}
foo(obj);
console.log(obj.value) // 2
// 例子2
var obj = {
    value: 1
};
function foo(o) {
    o = 2;
    console.log(o); //2
}
foo(obj);
console.log(obj.value) // 1

解释:

对于复杂的数据类型,函数内部的临时变量和传入的参数指向同一个内存地址,所以有例子一,我们能通过 o.value 找到内存中的 o,也就找到了外部的 obj,所以我们修改 o.value 值的时候,也会影响 obj 中的 value 值。

对于例子二,因为是直接对传入的参数进行了赋值操作,这会将内部参数 o 进行重新绑定,指向了一个新的地址,所以此时修改函数内部的值不会对外部有影响。

参考文章

https://segmentfault.com/q/1010000003023316

感谢你的阅读

先就记录这几个知识点吧,多了一次性也记不住,大概率你也不会来看第二遍

etch 是 XMLHttpRequest 的升级版,使用js脚本发出网络请求,但是与 XMLHttpRequest 不同的是,fetch 方式使用 Promise,相比 XMLHttpRequest 更加简洁。所以我们告别XMLHttpRequest,引入 fetch 如何使用?

一、fetch介绍

fetch() 是一个全局方法,提供一种简单,合理的方式跨网络获取资源。它的请求是基于 Promise 的,需要详细学习 Promise ,请点击《 Promise详解 》。它是专门为了取代传统的 xhr 而生的。

1.1、fetch使用语法

fetch(url,options).then((response)=>{
//处理http响应
},(error)=>{
//处理错误
})

url :是发送网络请求的地址。

options:发送请求参数,

  • body - http请求参数
  • mode - 指定请求模式。默认值为cros:允许跨域;same-origin:只允许同源请求;no-cros:只限于get、post和head,并且只能使用有限的几个简单标头。
  • cache - 用户指定缓存。
  • method - 请求方法,默认GET
  • signal - 用于取消 fetch
  • headers - http请求头设置
  • keepalive - 用于页面卸载时,告诉浏览器在后台保持连接,继续发送数据。
  • credentials - cookie设置,默认omit,忽略不带cookie,same-origin同源请求带cookie,inclue无论跨域还是同源都会带cookie。

1.2、response 对象

fetch 请求成功后,响应 response 对象如图:

  • status - http状态码,范围在100-599之间
  • statusText - 服务器返回状态文字描述
  • ok - 返回布尔值,如果状态码2开头的,则true,反之false
  • headers - 响应头
  • body - 响应体。响应体内的数据,根据类型各自处理。
  • type - 返回请求类型。
  • redirected - 返回布尔值,表示是否发生过跳转。

1.3、读取内容方法

response 对象根据服务器返回的不同类型数据,提供了不同的读取方法。分别有:

  1. response.text() -- 得到文本字符串
  2. response.json() - 得到 json 对象
  3. response.blob() - 得到二进制 blob 对象
  4. response.formData() - 得到 fromData 表单对象
  5. response.arrayBuffer() - 得到二进制 arrayBuffer 对象

上述 5 个方法,返回的都是 promise 对象,必须等到异步操作结束,才能得到服务器返回的完整数据。

1.4、response.clone()

stream 对象只能读取一次,读取完就没了,这意味着,上边的五种读取方法,只能使用一个,否则会报错。

因此 response 对象提供了 clone() 方法,创建 respons 对象副本,实现多次读取。如下:将一张图片,读取两次:

const response1 = await fetch('flowers.jpg');
const response2 = response1.clone();

const myBlob1 = await response1.blob();
const myBlob2 = await response2.blob();

image1.src = URL.createObjectURL(myBlob1);
image2.src = URL.createObjectURL(myBlob2);

1.4、response.body()

body 属性返回一个 ReadableStream 对象,供用户操作,可以用来分块读取内容,显示下载的进度就是其中一种应用。

const response = await fetch('flower.jpg');
const reader = response.body.getReader();
while(true) {
  const {done, value} = await reader.read();
  if (done) {
    break;
  }
  console.log(`Received ${value.length} bytes`)
}

response.body.getReader() 返回一个遍历器,这个遍历器 read() 方法每次都会返回一个对象,表示本次读取的内容块。

二、请求时 POST 和 GET 分别处理

请求方式不同,传值方式也不同。xhr 会分别处理 get 和 post 数据传输,还有请求头设置,同样 fetch 也需要分别处理。

2.1、get 方式

只需要在url中加入传输数据,options中加入请求方式。如下面代码所示:

<input type="text" id="user"><br>
<input type="password" id="pas"><br>
<button onclick="login()">提交</button>
<script>
 function login(){
  fetch(`http://localhost:80/fetch.html?user=${user.value}&pas=${pas.value}`,{
   method:'GET'
  }).then(response=>{
   console.log('响应',response)
  })
 }
</script>

2.2、post 方式

使用 post 发送请求时,需要设置请求头、请求数据等。

将上个实例,改写成 post 方式提交数据,代码如下:

fetch(`http://localhost:80/ES6练习题/53fetch.html`,{
 method:'POST',
 headers:{
  'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'
 },
 body:`user=${user.value}&pas=${pas.value}`
 }).then(response=>{
  console.log('响应',response)
})

如果是提交json数据时,需要把json转换成字符串。如

body:JSON.stringify(json)

如果提交的是表单数据,使用 formData转化下,如:

body:new FormData(form)

上传文件,可以包含在整个表单里一起提交,如:

const input = document.querySelector('input[type="file"]');

const data = new FormData();
data.append('file', input.files[0]);
data.append('user', 'foo');

fetch('/avatars', {
  method: 'POST',
  body: data
});

上传二进制数据,将 bolb 或 arrayBuffer 数据放到body属性里,如:

let blob = await new Promise(resolve =>   
  canvasElem.toBlob(resolve,  'image/png')
);

let response = await fetch('/article/fetch/post/image', {
  method:  'POST',
  body: blob
});

三、fetch 常见坑

3.1、fetch兼容性

fetch原生支持率如图:

fetch 是相对较新的技术,IE浏览器不支持,还有其他低版本浏览器也不支持,因此如果使用fetch时,需要考虑浏览器兼容问题。

解决办法:引入 polyfill 完美支持 IE8 以上。

  • 由于 IE8 是 ES3,需要引入 ES5 的 polyfill: es5-shim, es5-sham
  • 引入 Promise 的 polyfill:es6-promise
  • 引入 fetch 探测库:fetch-detector
  • 引入 fetch 的 polyfill: fetch-ie8
  • 可选:如果你还使用了 jsonp,引入 fetch-jsonp
  • 可选:开启 Babel 的 runtime 模式,现在就使用 async/await

polyfill 的原理就是探测fetch是否支持,如果不支持则用 xhr 实现。支持 fetch 的浏览器,响应中文会乱码,所以使用 fetch-detector 和 fetch-ie8 解决乱码问题。

3.2、fetch默认不带cookie

传递cookie时,必须在header参数内加上 credentials:'include',才会像 xhr 将当前cookie 带有请求中。

3.3、异常处理

fetch 不同于 xhr ,xhr 自带取消、错误等方法,所以服务器返回 4xx 或 5xx 时,是不会抛出错误的,需要手动处理,通过 response 中的 status 字段来判断。

sp中四种传递参数的方法,我觉得总结一下,挺好的,以备后用!

1、form表单

2、request.setAttribute();和request.getAttribute();

3、超链接:<a herf="index.jsp"?a=a&b=b&c=c>name</a>

1、form表单

form.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 form.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 
 <h2 style="font-family:arial;color:red;font-size:25px;text-align:center">登录页面</h2> 
 
 <form action="result.jsp" method="get" align="center"> 
 姓名:<input type="text" name="name" size="20" value="" maxlength="20"><br/> 
 
 密码:<input type="password" name="password" size="20" value="" maxlength="20"><br/> 
 
 <!--在爱好前空一个空格,是为了排版好看些--> 
 
 爱好:<input type="checkbox" name="hobby" value="唱歌">唱歌 
 <input type="checkbox" name="hobby" value="足球">足球 
 <input type="checkbox" name="hobby" value="篮球">篮球<br/><br/> 
 
 <input type="submit" name="submit" value="登录"> 
 <input type="reset" name="reset" value="重置"><br/> 
 </form> 
 
 </body> 
</html>

result.jsp:

 1 <%@page language="java" import="java.util.*" pageEncoding="GB2312"%> 
 2 <html> 
 3 <head> 
 4 <title> 
 5 result.jsp file 
 6 </title> 
 7 </head> 
 8 
 9 <body bgcolor="ffffff"> 
10 <% 
11 request.setCharacterEncoding("GB2312"); 
12 
13 String name=request.getParameter("name"); 
14 name=new String(name.getBytes("iso-8859-1"),"GB2312"); 
15 
16 String pwd=request.getParameter("password"); 
17 String[] hobby=request.getParameterValues("hobby");//注意这里的函数是getParameterValues()接受一个数组的数据 
18 
19 %> 
20 
21 <% 
22 if(!name.equals("") && !pwd.equals("")) 
23 { 
24 %> 
25 
26 您好!登录成功!<br/> 
27 姓名:<%=name%><br/> 
28 密码:<%=pwd%><br/> 
29 爱好:<% 
30 for(String ho: hobby) 
31 { 
32 ho=new String(ho.getBytes("iso-8859-1"),"GB2312"); 
33 out.print(ho+" "); 
34 } 
35 %> 
36 <% 
37 } 
38 else 
39 { 
40 %> 
41 请输入姓名或密码! 
42 <% 
43 } 
44 %> 
45 </body> 
46 </html>

注意:form表单的提交方式为get,在参数传递时会遇到中文乱码的问题,一个简单的解决方法是,将接受到的字符串先转换成一个byte数组,再用String构造一个新的编码格式的String,如:

1 String name=request.getParameter("name"); 
2 name=new String(name.getBytes("iso-8859-1"),"GB2312"); 

如果form表单的提交方式为post,解决乱码问题的简单办法是,使用 request.setCharacterEncoding("GB2312");设置request的编码方式。

为什么会出现中文乱码问题呢?因为Tomcat服务器默认的系统编码方式为iso- 8859-1,你传递参数给服务器时,使用的是默认的iso-8859-1的编码方式,但是服务器向你返回信息时,是按page指令中设置的编码方式, 如:<%@page language="java" import="java.util.*" pageEncoding="GB2312"%>,这样就混合了两种编码方式,所以会出现乱码,所以解决之道就是统一传递和接收的编码方式。

2、request.setAttribute()和request.getAttribute()

set.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 set.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <% 
 request.setAttribute("name","心雨"); 
 %> 
 <jsp:forward page="get.jsp"/> 
 </body> 
</html>

get.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 get.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <% 
 out.println("传递过来的参数是:"+request.getAttribute("name")); 
 %> 
 </body> 
</html> 

request.setAttribute()和request.getAttribute()是配合<jsp:forward>或是include指令来实现的。

3、超链接:<a herf="index.jsp?a=a&b=b&c=c">name</a>

href.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 href.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <a href="getHerf.jsp?name=心雨&password=123">传递参数</a> 
 </body> 
</html> 

getHref.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 getHref.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <% 
 String name=request.getParameter("name"); 
 name=new String(name.getBytes("iso-8859-1"),"gb2312"); 
 
 out.print("name:"+name); 
 %> 
 <br/> 
 <% 
 out.print("password:"+request.getParameter("password")); 
 %> 
 </body> 
</html> 

这种传递参数的方法和form表单的get方式类似,是通过地址栏传递的参数,其乱码解决方法也和form 的get方式一样。

4、<jsp:param>

param.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 param.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 
 <%request.setCharacterEncoding("GB2312");%> 
 
 <jsp:forward page="getParam.jsp"> 
 <jsp:param name="name" value="心雨"/> 
 <jsp:param name="password" value="123"/> 
 </jsp:forward> 
 
 </body> 
</html>

getParam.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 getParam.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <% 
 String name=request.getParameter("name"); 
 out.print("name:"+name); 
 %> 
 <br/> 
 <% 
 out.print("password:"+request.getParameter("password")); 
 %> 
 </body> 
</html> 

这里发现了一个奇怪的问题,还是在中文乱码的问题上,在form表单的例子中,如果传递方式为post,则只需要在接收参数的页面设置request的编 码方式就可以了,即request.setCharacterEncoding("GB2312");,注意是在接收参数的页面,如果将该句放到form 表单里,那么不起作用,仍然是乱码。而在本例中,为了使传递的参数不出现乱码,却是将 request.setCharacterEncoding("GB2312");放在发送参数的页面中,才会正常显示中文,放在接收参数的页面中,不起 作用。也许这就是<jsp:param>和form表单传递参数不同的地方。为什么会有这个不同呢?可能是因为form表单中的参数是由客户 端传送到服务端上的,需要经过一个request的打包过程,但是<jsp:param>传递的参数本身就是在服务器端的,不需要经历由客户 端到服务端这么一个过程,但是服务器里的参数传递是这么回事呢?这个问题,我不知道了!真是知识是一个扩大的圆圈,你知道的越多,那么不知道的就越多!努 力吧!