前端js 字符串 数组方法

split() 字符串方法,根据指定字符截取,同时转换为数组,不会改变原来字符串

const text = "abc";
const chars = text.split("b");
console.log(chars);
//['a', 'c']
slice() 数组和字符串方法,根据索引截取字符串或数组
const text = "abcdefg";
const chars = text.split("cd");
console.log(chars);
//['ab', 'efg']

forEach 数组方法,循环数组,第一个参数是数组中的每一项,第二个参数是索引

const text = ["a", "b", "c", "d", "e", "f", "g"];
text.forEach((item, index) => {
  console.log(item, index);
  //a 0
  //b 1
  //c 2 ....
});

展开运算符,字符串转化为数组

const text = "abcdefg";
const chars = [ ...text ];
console.log(chars);
//['a', 'b', 'c', 'd', 'e', 'f', 'g']

解构赋值,字符串转化为数组

const text = "abcdefg";
const [...chars] = text;
console.log(chars);
//['a', 'b', 'c', 'd', 'e', 'f', 'g']

你可能感兴趣的:(前端,javascript,开发语言)