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

js 字符串与数组的操作

序:用的时候,有时会疑惑,这个怎么和字符串(数组)的用法是一样的,难道它们是同一个,其实是它们的属性一样,但并不通用

数组某个对象值更新

updateArr(){
  let bleList = [{id:1,name:"",sbId:""},{id:2,name:"",sbId:""},{id:3,name:"",sbId:""},{id:4,name:"",sbId:""},{id:5,name:"",sbId:""},{id:6,name:"",sbId:""}];
  // 1、使用map遍历
  bleList = bleList.map(item => {
    if (item.id === 2) {
      return {
        ...item,
        name: "haha",
        sbId: "abcdefghijkl"
      };
    }
    return item;
  });
  // 2、使用索引赋值
  // const index = bleList.findIndex(item => item.id === 2);
  // bleList[index].name = "haha";
  // bleList[index].sbId = "abcdefghijkl";
  // console.log(bleList);
},

字符串与数组的长度(.length)、索引、遍历

let str = "Hello";
let arr = [a, b, c];
// 长度
let strLen = str.length;
let arrLen = arr.length;
console.log(strLen); // 5
console.log(arrLen); // 3
// 索引获取
console.log(str[0]); // "H"
console.log(arr[0]); // a
console.log(str[strLen - 1]); // "o"
console.log(arr[arrLen - 1]); // c
// 遍历与迭代
for (let char of str) {
  console.log(char);
}
for (let elem of arr) {
  console.log(elem);
}
// 拼接与连接
let str2 = "World";
console.log(str + " " + str2); // "Hello World"
console.log(arr.join("-")); // "a-b-c"

字符串与数组的切割方法

// 数组的 splice 和 slice 方法
let arr = [a, b, c, d, e];
let removedArr = arr.splice(1, 2); // 移除索引1和2的元素
console.log(arr); // [a, d, e]
console.log(removedArr); // [b, c]
let slicedArr = arr.slice(0, 2); // 从索引0开始到索引1,不包括2
console.log(slicedArr ); // [a, d]

// 字符串的 split 和 slice 方法
let text = "Hello, World!";
let words = text.split(", "); // 根据逗号和空格分割
console.log(words); // ["Hello", "World!"]
let sliceText = text.slice(7, 12); // 提取索引7到11的字符,不包括12
console.log(sliceText); // "World"

字符串与数组的相互转换

let arr = [a, b, c];
let str = arr.toString();
// let str = arr.join(',');
console.log(str); // "a,b,c"

let str2 = "Hello";
let arr2 = Array.from(str2);
console.log(arr2); // ["H", "e", "l", "l", "o"]

// 动态拼接
let strAct = arr.reduce((acc, curr) => acc + '-' + curr, '').slice(1);
console.log(strAct); // "a-b-c"
let name = "Tom";
let greet = `Hello, ${name}!`;
console.log(greet); // "Hello, Tom!"

记录一下字符串与数组中易混淆的方法,正所谓好记性不如烂笔头。


http://www.kler.cn/news/357022.html

相关文章:

  • python【装饰器】
  • python中_init_.py 到底有啥用?
  • nvm安装,node多版本管理
  • 多级缓存-案例导入说明
  • 自定义多级联动选择器指南(uni-app)
  • Spring Boot实现的电影评论系统开发
  • 开发工具(上)
  • 【数据结构与算法】第2课—数据结构之顺序表
  • 对于从vscode ssh到virtualBox的timeout记录
  • 【JavaScript】LeetCode:76-80
  • 【RestTemplate】重试机制详解
  • 生成式人工智能如何帮助我们更有效地传达信息
  • 《使用Gin框架构建分布式应用》阅读笔记:p88-p100
  • L1正则化详解
  • 【编程基础知识】《Java 基础探秘:return、break、continue、label、switch 与 enum 的深度解析》
  • 网络空间安全之一个WH的超前沿全栈技术深入学习之路(二:渗透测试行业术语扫盲)作者——LJS
  • 基于SpringBoot+Vue的读书笔记共享平台的设计与实现
  • 「言必信」电源滤波器的尺寸、重量在哪些场景中是重要考虑因素
  • Wails 学习笔记:Wails核心思想理解
  • 标题:中阳国际:智能化金融平台助力全球化投资