<center>反转数组(两种方法)</center>

本文介绍了两种JavaScript数组反转的方法:一是创建新数组接收并返回,二是直接修改原数组。第一种方法通过遍历原数组并反向添加元素到新数组实现;第二种方法通过交换原数组元素位置完成反转。
a.第一种方法:创建一个新数组接收并返回;
   var arr1 = [1,2,3];
   var arr2 = reverse1(arr1);
   console.log(arr2);
   console.log(reverse1(arr1));
   //定义一个新数组,把老数组中的元素反向添加到新数组中
   function reverse1(array){
       var newArr = [];
       for(var i=array.length-1;i>=0;i--){
           newArr[newArr.length] = array[i];
       }
       return newArr;
   }
 
 
  b.第二种方法:直接修改原数组;
   var arr = [1,2,3];
   console.log(arr);
   console.log(reverse2(arr));
 
   //修改或者说翻转原数组,此方法没有返回值,所以只能打印原数组。
   function reverse2(array){
       for(var i=0;i<array.length/2;i++){
           var temp = array[i];
           array[i] = array[array.length-1-i];
           array[array.length-1-i] = temp;
       }
       return array;   //Array对象中的方法返回了一个数组。
   }
<template> <div class="app-container"> <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"> <el-form-item label="参数名称" prop="paramName"> <el-input v-model="queryParams.paramName" clearable @keyup.enter.native="handleQuery" /> </el-form-item> <el-form-item label="预警级别" prop="alertLevel"> <el-select v-model="queryParams.alertLevel" clearable filterable> <el-option v-for="dict in dict.type.alert_level" :key="dict.value" :label="dict.label" :value="dict.value" /> </el-select> </el-form-item> <el-form-item> <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button> <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> </el-form-item> </el-form> <el-row :gutter="10" class="mb8"> <el-col :span="1.5"> <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:deviceUnusual:add']">新增</el-button> </el-col> <el-col :span="1.5"> <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:deviceUnusual:edit']">修改</el-button> </el-col> <el-col :span="1.5"> <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:deviceUnusual:remove']">删除</el-button> </el-col> <el-col :span="1.5"> <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:deviceUnusual:export']">导出</el-button> </el-col> <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> </el-row> <el-table v-loading="loading" :data="deviceUnusualList"> <el-table-column label="设备ID" align="center" prop="deviceId" /> <!-- <el-table-column label="设备名称" align="center" prop="deviceId" > <template slot-scope="scope"> {{deviceList.find(item => item.deviceId == scope.row.deviceId) ? deviceList.find(item => item.deviceId == scope.row.deviceId).deviceName : '未知设备'}} </template> </el-table-column> --> <el-table-column label="参数名称" align="center" prop="paramName" /> <el-table-column label="阈值比较器" align="center" prop="thresholdComparator" /> <el-table-column label="阈值" align="center" prop="thresholdValue" /> <el-table-column label="预警级别" align="center" prop="alertLevel" > <template slot-scope="scope"> <dict-tag :options="dict.type.alert_level" :value="scope.row.alertLevel" /> </template> </el-table-column> <el-table-column label="操作" align="center" class-name="small-padding fixed-width"> <template slot-scope="scope"> <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:deviceUnusual:edit']">修改</el-button> <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:deviceUnusual:remove']">删除</el-button> </template> </el-table-column> </el-table> <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" /> <!-- 添加或修改设备类型对话框 --> <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body> <el-form ref="form" :model="form" :rules="rules" label-width="120px"> <el-form-item label="设备" prop="deviceId"> <el-select v-model="form.deviceId" clearable filterable> <el-option v-for="dict in deviceList" :key="dict.deviceId" :label="dict.deviceName" :value="dict.deviceId" /> </el-select> </el-form-item> <el-form-item label="参数名称" prop="paramName"> <el-input v-model="form.paramName" /> </el-form-item> <el-form-item label="阈值比较器" prop="thresholdComparator"> <el-input v-model="form.thresholdComparator" /> <!-- <el-select v-model="value" placeholder="请选择"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select> --> </el-form-item> <el-form-item label="阈值" prop="thresholdValue"> <el-input v-model="form.thresholdValue" /> </el-form-item> <el-form-item label="预警级别" prop="alertLevel"> <el-select v-model="form.alertLevel" clearable filterable> <el-option v-for="dict in dict.type.alert_level" :key="dict.value" :label="dict.label" :value="dict.value" /> </el-select> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button type="primary" @click="submitForm">确 定</el-button> <el-button @click="cancel">取 消</el-button> </div> </el-dialog> </div> </template> <script> import { listDeviceUnusual, getDeviceUnusual, delDeviceUnusual, updateDeviceUnusual, addDeviceUnusual } from "@/api/system/deviceUnusual"; import { listDevice } from "@/api/system/device"; export default { name: "DeviceUnusual", dicts: ['alert_level'], data() { return { // 遮罩层 loading: true, // 选中数组 ids: [], // 非单个禁用 single: true, // 非多个禁用 multiple: true, // 显示搜索条件 showSearch: true, // 总条数 total: 0, // 设备类型表格数据 deviceUnusualList: [], deviceList: [], // 弹出层标题 title: "", // 是否显示弹出层 open: false, // 查询参数 queryParams: { pageNum: 1, pageSize: 10, thresholdId: null, deviceId: null, paramName: null, deviceName: null, minValue: null, maxValue: null, }, // 表单参数 form: {}, // 表单校验 rules: { deviceId: [ { required: true, message: "设备名称不能为空", trigger: "blur" } ], paramName: [ { required: true, message: "参数名称不能为空", trigger: "blur" } ], } }; }, created() { this.getList(); }, methods: { /** 查询设备类型列表 */ getList() { this.loading = true; listDeviceUnusual(this.queryParams).then(response => { this.deviceUnusualList = response.rows; this.total = response.total; this.loading = false; }); listDevice().then(response => { this.deviceList = response.rows; // this.total = response.total; // console.log(this.deviceList) }); }, // 取消按钮 cancel() { this.open = false; this.reset(); }, // 表单重置 reset() { this.form = { thresholdId: null, deviceId: null, paramName: null, deviceName: null, minValue: null, maxValue: null, }; this.resetForm("form"); }, /** 搜索按钮操作 */ handleQuery() { this.queryParams.pageNum = 1; this.getList(); }, /** 重置按钮操作 */ resetQuery() { this.resetForm("queryForm"); this.handleQuery(); }, handleAdd() { this.reset(); this.open = true; this.title = "添加设备"; }, /** 修改按钮操作 */ handleUpdate(row) { this.reset(); const thresholdId = row.thresholdId || this.ids getDeviceUnusual(thresholdId).then(response => { this.form = response.data; this.open = true; this.title = "修改"; }); }, /** 提交按钮 */ submitForm() { this.$refs["form"].validate(valid => { if (valid) { if (this.form.thresholdId != null) { updateDeviceUnusual(this.form).then(response => { this.$modal.msgSuccess("修改成功"); this.open = false; this.getList(); }); } else { addDeviceUnusual(this.form).then(response => { this.$modal.msgSuccess("新增成功"); this.open = false; this.getList(); }); } } }); }, /** 删除按钮操作 */ handleDelete(row) { const thresholdIds = row.thresholdId || this.ids; this.$modal.confirm('是否确认删除此设备的数据项?').then(function () { return delDeviceUnusual(thresholdIds); }).then(() => { this.getList(); this.$modal.msgSuccess("删除成功"); }).catch(() => { }); }, /** 导出按钮操作 */ handleExport() { this.download('/system/deviceParamThreshold/export', { ...this.queryParams }, `deviceUnusual_${new Date().getTime()}.xlsx`) } } }; </script>为什么新增时输入的是<列表阈值比较器显示<
08-12
<template> <div class="app-container"> <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"> <el-form-item label="案列标题" prop="title"> <el-input v-model="queryParams.title" placeholder="请输入案列标题" clearable @keyup.enter.native="handleQuery" /> </el-form-item> <el-form-item label="发布日期"> <el-date-picker v-model="daterangePublishDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" ></el-date-picker> </el-form-item> <el-form-item label="状态" prop="status"> <el-select v-model="queryParams.status" placeholder="请选择状态" clearable> <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" /> </el-select> </el-form-item> <el-form-item> <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button> <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> </el-form-item> </el-form> <!-- 操作按钮区域 --> <el-row :gutter="10" class="mb8"> <el-col :span="1.5"> <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['incorruptible:case:add']" >新增</el-button> </el-col> <el-col :span="1.5"> <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['incorruptible:case:edit']" >修改</el-button> </el-col> <el-col :span="1.5"> <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['incorruptible:case:remove']" >删除</el-button> </el-col> <el-col :span="1.5"> <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['incorruptible:case:export']" >导出</el-button> </el-col> <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> </el-row> <!-- 数据表格 --> <el-table v-loading="loading" :data="caseList" @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55" align="center" /> <el-table-column label="案例ID" align="center" prop="articleId" /> <el-table-column label="案列标题" align="center" prop="title" /> <el-table-column label="发布日期" align="center" prop="publishDate" width="180"> <template slot-scope="scope"> <span>{{ parseTime(scope.row.publishDate, '{y}-{m}-{d}') }}</span> </template> </el-table-column> <el-table-column label="状态" align="center" prop="status"> <template slot-scope="scope"> <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/> </template> </el-table-column> <el-table-column label="操作" align="center" class-name="small-padding fixed-width"> <template slot-scope="scope"> <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['incorruptible:case:edit']" >修改</el-button> <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['incorruptible:case:remove']" >删除</el-button> </template> </el-table-column> </el-table> <!-- 分页组件 --> <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" /> </div> </template> <script> import { listCase, delCase } from "@/api/incorruptible/case"; export default { name: "Case", dicts: ['sys_normal_disable'], data() { return { // 遮罩层 loading: true, // 选中数组 ids: [], // 非单个禁用 single: true, // 非多个禁用 multiple: true, // 显示搜索条件 showSearch: true, // 总条数 total: 0, // 廉洁标准案例表格数据 caseList: [], // 弹出层标题 title: "", // 是否显示弹出层 open: false, // 状态时间范围 daterangePublishDate: [], // 查询参数 queryParams: { pageNum: 1, pageSize: 10, title: null, publishDate: null, status: null, }, // Quill编辑器配置 editorOptions: { placeholder: '请输入内容', theme: 'snow', modules: { toolbar: { container: [ ['bold', 'italic', 'underline', 'strike'], ['blockquote', 'code-block'], [{ 'header': 1 }, { 'header': 2 }], [{ 'list': 'ordered'}, { 'list': 'bullet' }], [{ 'script': 'sub'}, { 'script': 'super' }], [{ 'indent': '-1'}, { 'indent': '+1' }], [{ 'direction': 'rtl' }], [{ 'size': ['small', false, 'large', 'huge'] }], [{ 'header': [1, 2, 3, 4, 5, 6, false] }], [{ 'color': [] }, { 'background': [] }], [{ 'font': [] }], [{ 'align': [] }], ['clean'], ['link', 'image'] // 图片上传按钮 ], // 图片按钮的自定义处理 handlers: { 'image': this.handleImageButtonClick } } } }, // 保存Quill实例 quillInstance: null, // 表单参数 form: {}, // 表单校验 rules: { } } }, created() { this.getList() }, methods: { /** 查询廉洁标准案例列表 */ getList() { this.loading = true this.queryParams.params = {} if (null != this.daterangePublishDate && '' != this.daterangePublishDate) { this.queryParams.params["beginPublishDate"] = this.daterangePublishDate[0] this.queryParams.params["endPublishDate"] = this.daterangePublishDate[1] } listCase(this.queryParams).then(response => { this.caseList = response.rows this.total = response.total this.loading = false }) }, // 取消按钮 cancel() { this.open = false this.reset() }, // 表单重置 reset() { this.form = { articleId: null, title: null, publishDate: null, content: null, status: null, createBy: null, createTime: null, updateBy: null, updateTime: null } this.resetForm("form") }, /** 搜索按钮操作 */ handleQuery() { this.queryParams.pageNum = 1 this.getList() }, /** 重置按钮操作 */ resetQuery() { this.daterangePublishDate = [] this.resetForm("queryForm") this.handleQuery() }, // 多选框选中数据 handleSelectionChange(selection) { this.ids = selection.map(item => item.articleId) this.single = selection.length!==1 this.multiple = !selection.length }, /** 新增按钮操作 */ handleAdd() { this.$router.push({ name: 'CaseAdd' }); }, /** 修改按钮操作 */ handleUpdate(row) { const articleId = row.articleId || this.ids[0]; this.$router.push({ name: 'CaseEdit', params: { articleId: articleId } }); }, // 编辑器准备就绪 onEditorReady(editor) { this.quillInstance = editor; }, // 图片按钮点击事件处理 handleImageButtonClick() { if (!this.quillInstance) return; // 创建隐藏的文件输入元素 const input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'image/*'); input.style.display = 'none'; document.body.appendChild(input); input.click(); // 文件选择后处理 input.onchange = () => { if (!input.files || !input.files[0]) return; const file = input.files[0]; // 检查文件大小 if (file.size > 5 * 1024 * 1024) { this.$modal.msgError('图片大小不能超过5MB'); return; } // 上传图片 this.uploadImage(file) .then(imageUrl => { // 获取当前光标位置 const range = this.quillInstance.getSelection(); if (range) { // 在光标位置插入图片 this.quillInstance.insertEmbed(range.index, 'image', imageUrl); // 移动光标到图片后面 this.quillInstance.setSelection(range.index + 1); } }) .catch(error => { console.error('图片上传失败:', error); this.$modal.msgError('图片上传失败'); }) .finally(() => { // 清理文件输入元素 document.body.removeChild(input); }); }; }, // 图片上传方法 uploadImage(file) { return new Promise((resolve, reject) => { const formData = new FormData(); formData.append('file', file); const uploadUrl = process.env.VUE_APP_BASE_API + '/file/upload'; axios.post(uploadUrl, formData, { headers: { 'Authorization': 'Bearer ' + getToken(), 'Content-Type': 'multipart/form-data' } }).then(response => { const res = response.data; // 处理不同返回格式 let imageUrl = ''; if (res.code === 200 && res.data) { if (typeof res.data === 'string') { imageUrl = res.data; } else if (res.data.url) { imageUrl = res.data.url; } else if (res.data.value) { imageUrl = String(res.data.value); } if (imageUrl) { // 确保URL格式正确 if (!imageUrl.startsWith('http')) { imageUrl = process.env.VUE_APP_BASE_API + imageUrl; } resolve(imageUrl); } else { reject('无法解析图片URL'); } } else { reject(res.msg || '图片上传失败'); } }).catch(error => { console.error('图片上传失败:', error); reject('上传失败: ' + (error.message || '网络错误')); }); }); }, // 富文本内容JSON转义处理 escapeHtmlForJson(html) { if (!html) return ''; // 1. 保留已有的   实体,将其转换为 \u00a0 let processedHtml = html.replace(/ /g, '\\u00a0'); // 2. 处理行首空格(缩进)和连续空格 // 将行首的连续空格(包括制表符)转换为 \u00a0 processedHtml = processedHtml.replace(/^[ \t]+/gm, (match) => { return '\\u00a0'.repeat(match.length); }); // 3. 处理非行首的连续空格(两个或以上) processedHtml = processedHtml.replace(/([^ \t\n\r])([ \t]{2,})/g, (match, prefix, spaces) => { return prefix + '\\u00a0'.repeat(spaces.length); }); // 4. 转义其他JSON特殊字符 processedHtml = processedHtml .replace(/\\/g, '\\\\') // 转义反斜杠 .replace(/"/g, '\\"') // 转义双引号 .replace(/\//g, '\\/') // 转义斜杠 .replace(/\n/g, '\\n') // 转义换行符 .replace(/\r/g, '\\r') // 转义回车符 .replace(/\t/g, '\\t') // 转义制表符 .replace(/\f/g, '\\f') // 转义换页符 .replace(/</g, '\\u003c') // 转义小于号 .replace(/>/g, '\\u003e'); // 转义大于号 return processedHtml; }, // JSON转义内容反转义处理 unescapeHtmlFromJson(escapedHtml) { if (!escapedHtml) return ''; return escapedHtml .replace(/\\u00a0/g, ' ') // 将\u00a0转回为  .replace(/\\u003c/g, '<') // 转义小于号 .replace(/\\u003e/g, '>') // 转义大于号 .replace(/\\"/g, '"') // 转义双引号 .replace(/\\\//g, '/') // 转义斜杠 .replace(/\\\\/g, '\\') // 转义反斜杠 .replace(/\\n/g, '\n') // 转义换行符 .replace(/\\r/g, '\r') // 转义回车符 .replace(/\\t/g, '\t') // 转义制表符 .replace(/\\f/g, '\f'); // 转义换页符 }, /** 提交按钮 */ submitForm() { this.$refs["form"].validate(valid => { if (valid) { // 检查富文本内容是否为空 if (!this.form.content || this.form.content === '<p><br></p>') { this.$modal.msgWarning('案例内容不能为空'); return; } // 复制表单数据并转义富文本内容 const formData = { ...this.form, // 关键:对富文本内容进行JSON转义 content: this.escapeHtmlForJson(this.form.content) }; if (this.form.articleId != null) { updateCase(formData).then(response => { this.$modal.msgSuccess("修改成功"); this.open = false; this.getList(); }); } else { addCase(formData).then(response => { this.$modal.msgSuccess("新增成功"); this.open = false; this.getList(); }); } } }); }, /** 删除按钮操作 */ handleDelete(row) { const articleIds = row.articleId || this.ids this.$modal.confirm('是否确认删除廉洁标准案例编号为"' + articleIds + '"的数据项?').then(function() { return delCase(articleIds) }).then(() => { this.getList() this.$modal.msgSuccess("删除成功") }).catch(() => {}) }, /** 导出按钮操作 */ handleExport() { this.download('incorruptible/case/export', { ...this.queryParams }, `case_${new Date().getTime()}.xlsx`) } } } </script> 该页面跳转详情页进行修改后返回这个页面,不能自动刷新数据,我想要每次跳转到这个页面都自动刷新
08-23
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值