当前位置:   article > 正文

Array.prototype.slice.call()方法详解

array.prototype.slice.call
  • slice:用来截取截取字符串方法
  • Array: javascript的一个引用类型,其原型prototype上有一个方法叫slice
  • call和apply : 用来改变对象中函数内部的this引用,使得函数可以随便换‘妈妈’

为什么不直接用 arguments.slice(1)呢 不是一样的么?

答案是不一样。

Array.prototype.slice.call(arguments, 1)可以理解成是让arguments转换成一个数组对象,让arguments具有slice()方法。要是直接写arguments.slice(1)会报错。

arguments 是object 不是Array ,他的原型上没有slice方法

原理:

Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组

  1. var a={length:2,0:'first',1:'second'};//类数组,有length属性,长度为2,第0个是first,第1个是second
  2. console.log(Array.prototype.slice.call(a,0));// ["first", "second"],调用数组的slice(0);
  3. var a={length:2,0:'first',1:'second'};
  4. console.log(Array.prototype.slice.call(a,1));//["second"],调用数组的slice(1);
  5. var a={0:'first',1:'second'};//去掉length属性,返回一个空数组
  6. console.log(Array.prototype.slice.call(a,0));//[]
  7. function test(){
  8. console.log(Array.prototype.slice.call(arguments,0));//["a", "b", "c"],slice(0)
  9. console.log(Array.prototype.slice.call(arguments,1));//["b", "c"],slice(1)
  10. }
  11. test("a","b","c");

将函数的实际参数转换成数组的方法:

1、

var args = Array.prototype.slice.call(arguments);

2、

  1. var args = [];
  2. for (var i = 1; i < arguments.length; i++) {
  3. args.push(arguments[i]);
  4. }

 3、

  1. var toArray = function(s){
  2. try{
  3. return Array.prototype.slice.call(s);
  4. } catch(e){
  5. var arr = [];
  6. for(var i = 0,len = s.length; i < len; i++){
  7. //arr.push(s[i]);
  8. arr[i] = s[i]; //据说这样比push快
  9. }
  10. return arr;
  11. }
  12. }

将函数的实际参数转换成数组的方法的实际应用:

表单申请时,upload组件上传多张图片时候,能够左右切换预览所有上传的图片;

表单申请后,打开upload组件也能够预览多张图片

 

代码如下

  1. import Viewer from "viewerjs";
  2. 预览组件的版本号:"viewerjs": "^1.10.5",
  3. /**关闭图片 */
  4. handleCancel = () => this.setState({ previewVisible: false });
  5. /**处理图片 */
  6. handlePreview = async (file: UploadFile, className: string) => {
  7. if (!file.url && !file.preview) {
  8. file.preview = await getBase64(file.originFileObj as Blob) as string;
  9. }
  10. if ([".pdf", ".docx", ".doc"].some(i => file.response?.data.replace(/\s/g, "")?.includes(i)) || [".pdf", ".docx", ".doc"].some(i => file.url?.replace(/\s/g, "")?.includes(i))) {
  11. this.setState({
  12. previewImage: file?.url || file?.preview as string,
  13. previewVisible: true,
  14. fileUrl: file.response?.data.replace(/\s/g, ""),
  15. });
  16. } else {
  17. const dom = document.querySelector(`.${className} .ant-upload-list`);
  18. const url = file.url || file.thumbUrl || file.preview;
  19. const domSrcList = Array.prototype.slice.call(document.querySelectorAll(`.${className} .ant-upload-list img`)).map(i => i.src);
  20. if (dom) {
  21. const gallery = new Viewer(dom as HTMLElement, {
  22. initialViewIndex: domSrcList.indexOf(url) !== -1 ? domSrcList.indexOf(url) : 0,
  23. hidden: () => {
  24. gallery.destroy();
  25. },
  26. });
  27. gallery.show();
  28. }
  29. }
  30. }
  31. /** 处理上传 */
  32. handleChange = async (data: UploadChangeParam<UploadFile<any>>) => {
  33. const fun = () => {
  34. if (data.file.response) {
  35. if (data.file.response.data) {
  36. for (let i of data.fileList) {
  37. if (i.thumbUrl?.includes("base64")) {
  38. i.thumbUrl = i.response?.data || i.thumbUrl;
  39. }
  40. }
  41. }
  42. }
  43. }
  44. fun();
  45. }
  46. render() {
  47. <div className="clearfix sycnssmj">
  48. <Form.Item>
  49. {getFieldDecorator("sycnssmj", {
  50. valuePropName: "sycnssmj",
  51. getValueFromEvent: (e: UploadChangeParam) => {
  52. return e.fileList;
  53. },
  54. rules: [
  55. {
  56. required: checkType ? true : false,
  57. message: "文件必须上传!",
  58. },
  59. { validator: checkedUploadSuccess },
  60. ],
  61. initialValue: defaultValue && [...fileListFun(defaultValue.sycnssmj as File[])],
  62. })(<Upload
  63. accept="image/*,.pdf,.docx"
  64. key={JSON.stringify(defaultValue && [...fileListFun(defaultValue.sycnssmj as File[])])}
  65. defaultFileList={defaultValue && [...fileListFun(defaultValue.sycnssmj as File[])]}
  66. name="file"
  67. multiple
  68. transformFile={transformFile}
  69. listType="picture"
  70. action={`${window.config.backEnd}/api/v1/business/file/upload`}
  71. method="POST"
  72. headers={{
  73. Authorization: users && `Bearer ${users.access_token}`,
  74. }}
  75. disabled={globelDisable}
  76. onPreview={(file) => this.handlePreview(file, "sycnssmj")}
  77. onChange={this.handleChange}
  78. >
  79. {globelDisable ? null : <FileButton>{uploadButton}</FileButton>}
  80. </Upload>)}
  81. </Form.Item>
  82. </div>
  83. }

预览声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】

推荐阅读
相关标签