当前位置: 首页 > wzjs >正文

余姚 网站建设wordpress重命名

余姚 网站建设,wordpress重命名,制作招商加盟网站,常德网站建设技术🌟 解锁 indexOf、substring 和 JSON.stringify:从小程序图片上传看字符串魔法 ✨ 在 JavaScript 中,字符串操作和数据序列化是开发中不可或缺的技能。indexOf、substring 和 JSON.stringify 是三个简单却强大的工具,分别用于定位…

🌟 解锁 indexOfsubstringJSON.stringify:从小程序图片上传看字符串魔法 ✨

在 JavaScript 中,字符串操作和数据序列化是开发中不可或缺的技能。indexOfsubstringJSON.stringify 是三个简单却强大的工具,分别用于定位子字符串、提取片段和将对象转为 JSON 字符串。今天,我们将以一个微信小程序的图片上传功能为例,深入探索这三个方法如何协作处理图片 URL,确保数据高效传递到后台。

本文从实践出发,带你领略字符串操作的魅力!


🎬 示例场景:小程序图片上传

我们开发一个微信小程序,用户上传产品照片后,数据通过 saveFakeRegistration 函数保存到后台。以下是关键代码:

/*** 保存/修改假货登记* @param {Object} data - 要保存的假货登记数据* @param {Boolean} isSubmit - 是否为提交线上协助比对 (true: 提交, false: 暂存)* @returns {Promise} 请求结果的Promise*/
const saveFakeRegistration = (data, isSubmit = false) => {const sessionId = wx.getStorageSync('sessionId');const adminToken = wx.getStorageSync('admin_token');const inviteCodeId = wx.getStorageSync('inviteCodeId');const fakeRegistration = {...(data.id ? { id: data.id } : {}),productName: data.productName,productId: data.productId,purchaseChannel: data.channel || '',purchasePrice: data.price || '',contactInfo: data.contact || '',productPhotos: JSON.stringify((data.productImages || []).map(url => {const pathStart = url.indexOf('/', url.indexOf('//') + 2);return pathStart !== -1 ? url.substring(pathStart + 1) : url;})),purchaseRecords: JSON.stringify((data.purchaseRecords || []).map(url => {const pathStart = url.indexOf('/', url.indexOf('//') + 2);return pathStart !== -1 ? url.substring(pathStart + 1) : url;})),inviteCodeId: inviteCodeId,comparisonStatus: isSubmit ? 1 : 0};return new Promise((resolve, reject) => {wx.request({url: `${path.BASE_API_URL}/fakeRegistration/registration/save`,method: 'POST',data: fakeRegistration,header: {'content-type': 'application/json','token': adminToken,'Cookie': sessionId},success: (res) => {if (res.data.code === 0) resolve(res.data);else reject(new Error(res.data.msg || '保存失败'));},fail: (error) => reject(error)});});
};

我们将聚焦 productPhotospurchaseRecords 的处理,分析 indexOfsubstringJSON.stringify 如何将图片 URL 转为后台所需的格式。


🔍 认识 indexOf:定位大师

🌟 定义

indexOf 是字符串方法,用于查找子字符串第一次出现的位置。

🌈 语法

string.indexOf(searchValue[, fromIndex])
  • 返回值:索引(找到)或 -1(未找到)。

🎨 在代码中的应用

const pathStart = url.indexOf('/', url.indexOf('//') + 2);
  • 嵌套使用
    • url.indexOf('//'):找到协议后的双斜杠(如 https:// 中的 //)。
    • url.indexOf('/', url.indexOf('//') + 2):从双斜杠后开始,找下一个斜杠(路径起点)。
🎉 示例
const url = "https://example.com/path/to/image.jpg";
const doubleSlash = url.indexOf('//'); // 6
const pathStart = url.indexOf('/', doubleSlash + 2); // 19
console.log(pathStart); // 19
💡 作用
  • 定位 URL 中路径部分的起点(第三个斜杠),为后续提取做准备。

✂️ 认识 substring:裁剪专家

🌟 定义

substring 从字符串中提取指定范围的子字符串。

🌈 语法

string.substring(start[, end])
  • start:开始索引。
  • end(可选):结束索引(不包含)。
  • 返回值:提取的子字符串。

🎨 在代码中的应用

return pathStart !== -1 ? url.substring(pathStart + 1) : url;
  • 从第三个斜杠后(pathStart + 1)提取路径,去掉前面的协议和域名。
🎉 示例
const url = "https://example.com/path/to/image.jpg";
const pathStart = 19;
const path = url.substring(pathStart + 1); // "path/to/image.jpg"
console.log(path);
💡 作用
  • 提取图片的相对路径(如 "path/to/image.jpg"),确保数据简洁。

📦 认识 JSON.stringify:打包能手

🌟 定义

JSON.stringify 将 JavaScript 对象或数组转换为 JSON 字符串。

🌈 语法

JSON.stringify(value[, replacer[, space]])
  • value:要转换的值。
  • 返回值:JSON 格式的字符串。

🎨 在代码中的应用

productPhotos: JSON.stringify((data.productImages || []).map(url => {const pathStart = url.indexOf('/', url.indexOf('//') + 2);return pathStart !== -1 ? url.substring(pathStart + 1) : url;
})),
  • 将处理后的路径数组转为 JSON 字符串。
🎉 示例
const images = ["https://example.com/img1.jpg", "https://example.com/img2.jpg"];
const paths = images.map(url => url.substring(url.indexOf('/', url.indexOf('//') + 2) + 1));
console.log(JSON.stringify(paths)); // '["img1.jpg", "img2.jpg"]'
💡 作用
  • 将路径数组序列化为字符串,满足后台请求的格式。

🚀 三者的协作:从 URL 到路径

🎯 操作流程

  1. 输入data.productImages = ["https://example.com/path/to/image1.jpg", "https://example.com/path/to/image2.jpg"]
  2. indexOf:定位每个 URL 的路径起点。
    • "https://example.com/path/to/image1.jpg" -> pathStart = 19
  3. substring:提取路径。
    • url.substring(20) -> "path/to/image1.jpg"
  4. JSON.stringify:转为 JSON。
    • ["path/to/image1.jpg", "path/to/image2.jpg"] -> '["path/to/image1.jpg","path/to/image2.jpg"]'

🎨 结果

  • fakeRegistration.productPhotos'["path/to/image1.jpg","path/to/image2.jpg"]'
  • 发送到后台的数据简洁高效。

🌼 优化与思考

🎈 潜在问题

  • 格式假设:代码假设 URL 均为 "协议://域名/路径",若格式异常(如无 //),可能出错。
  • 效率:嵌套 indexOf 可读性稍低。

🎉 优化方案

  • 正则替代
    productPhotos: JSON.stringify((data.productImages || []).map(url => url.replace(/^https?:\/\/[^/]+\//, ''))),
    
    • 更简洁,但需测试兼容性。
  • 异常处理
    const pathStart = url.indexOf('/', url.indexOf('//') + 2);
    if (pathStart === -1) console.warn('Invalid URL:', url);
    

🎁 总结

indexOfsubstringJSON.stringify 是字符串处理与数据序列化的黄金组合:

  • indexOf 精准定位,解析 URL 结构。
  • substring 灵活裁剪,提取关键信息。
  • JSON.stringify 完美打包,适配后台。

在小程序图片上传中,三者协作将复杂 URL 转为简洁路径,展现了 JavaScript 的强大能力。试试这些方法,优化你的数据处理吧!


在这里插入图片描述


文章转载自:

http://Q3NuOoQM.wwjft.cn
http://cB5jJ4KB.wwjft.cn
http://Jp9gwDhM.wwjft.cn
http://MBfDZTVW.wwjft.cn
http://PGkpO6iZ.wwjft.cn
http://jIbJWfs0.wwjft.cn
http://jRtBX4kQ.wwjft.cn
http://RpgiK2At.wwjft.cn
http://Nl88d2po.wwjft.cn
http://fSTo57Aq.wwjft.cn
http://Bhc6zJCY.wwjft.cn
http://czG0naFQ.wwjft.cn
http://EJOYjVqW.wwjft.cn
http://MPKt2R2l.wwjft.cn
http://xa5CeZxH.wwjft.cn
http://xKRA1Urw.wwjft.cn
http://vpPhFaCx.wwjft.cn
http://3vuSQIHd.wwjft.cn
http://z06HwveW.wwjft.cn
http://zfdOXmbn.wwjft.cn
http://5jS0NrnI.wwjft.cn
http://DpB762nN.wwjft.cn
http://Ke2KPN2I.wwjft.cn
http://Dn39JWFD.wwjft.cn
http://qMlGai4z.wwjft.cn
http://RU6Unsyx.wwjft.cn
http://KOSPE5yf.wwjft.cn
http://Usnxr0F8.wwjft.cn
http://20bqWfpV.wwjft.cn
http://r80DUNhT.wwjft.cn
http://www.dtcms.com/wzjs/745045.html

相关文章:

  • 古镇免费网站建设婚庆策划公司装修
  • 上海网站营销ppt模板免费下载可爱
  • 沥林行业网站建设wordpress 产品属性
  • asp网站介绍做企业网站的字体大小要求
  • 建设一个商城网站要多少钱网站建设多少钱一年
  • 如何用dw做网站地图做推广网站多少钱
  • 做网站编写大兴模板网站建设
  • 宿州网站建设电话wordpress自动汉化
  • r语言做网站html5导航网站源码
  • 怎么刷网站点击量个人简介网页设计代码
  • 德安县建设局网站百度广告代运营公司
  • 简单网站制作教程开源房产网站源码
  • 网站备案幕布照片备案 网站
  • 网站源码怎样弄成网站wordpress 默认登陆
  • 邯郸建公司网站价格杭州百度快速排名提升
  • 租车网站建设方案网站版本功能列表
  • 直播视频网站开发长春新建火车站
  • 网站怎么广告投放国外电商网站如何做icp备案
  • 智林东莞网站建设公司百度引擎搜索网址
  • 信阳住房和城乡建设局网站响应式布局网站建设
  • 包头网站建设易通soso搜索引擎
  • 介绍几个免费的网站最好的搜索引擎排名
  • 广元建设网站要多少钱苏州网站制作
  • 怎么知道网站的ftp服装设计怎么学
  • wordpress能做图片站注册公司需要钱吗?多少费用
  • 遵义公司做网站专业建设标准
  • 做简约头像网站wordpress wp();
  • 网站建设初学升级不了wordpress
  • 太原百度seo排名软件seo网站建设方案
  • 开发网站语言别墅外观设计网站推荐