字符串和数组常用API
字符串API
<script>
// 字符串
let str = "ABc,123上学去";
// 长度
console.log(str.length);
// 索引
// 索引->元素
console.log(str[8]);
console.log(str.charAt(8));
// 元素->索引
console.log(str.indexOf("上"));
console.log(str.search("去"));
// 拼装
console.log(str.concat("啦啦啦"));
console.log(str + "哈哈哈");
console.log(`${str}嘻嘻嘻`);
// 替换replace
console.log(str.replace("123", "我"));
document.body.append(str.replace("123", "我"));
// 取子串
console.log(str.slice(1, 7));
// 知道取几个
console.log(str.substr(3, 4));
// 从后边取
console.log(str.substr(-4, 4));
// 变大写或者变小写
console.log(str.toLowerCase());
console.log(str.toUpperCase());
// 加a链接
console.log(str.link("https://baidu.com"));
document.body.insertAdjacentHTML(
"afterBegin",
str.link("https://baidu.com")
);
// 加粗
console.log(str.bold());
// document.body.append(str.bold());
document.body.insertAdjacentHTML("afterBegin", str.bold());
</script>
数组API
<script>
// 数组
// 字面量
let arr = [
1,
3,
4,
"我",
function () {
return 1;
},
{ x: 0.2, y: 0.5 },
];
console.log("-----------------------------");
console.log(arr);
console.log(Array.of(...arr));
// 类数组
let jon = {
0: "x",
1: "y",
2: "z",
length: 3,
};
console.log(Array.from(jon));
// 数组两端增删
// push\pop\unshift\shift
const myArray = [1, 5, 78, 34, 67, 99];
//查找
// filter find findIdex;
console.log(
myArray.filter(function (item) {
return item >= 20;
})
);
console.log(myArray.find((item) => item >= 20));
console.log(myArray.findIndex((item) => item >= 20));
// 归并reduce
res = myArray.reduce(function (acc, item, index, myArray) {
return acc + item;
}, 100);
console.log(res);
//遍历
let arr1 = myArray.forEach(
(item, index, arr) => (arr[index] = item * 10)
);
console.log(arr1);
console.log(myArray);
let arr2 = myArray.map((item) => item * 2);
console.log("-------------------");
console.log(arr2);
console.log(myArray);
//正序反序排列sort
console.log(myArray.sort((a, b) => a - b));
console.log(myArray.sort((a, b) => b - a));
// 数组转字符串toString
// 数组的slice
console.log(myArray.slice(1, 4));
// 删除新增替换splice
// 默认删除
console.log(myArray.splice(1, 2));
console.log(myArray);
// 新增
console.log(myArray.splice(1, 0, "张先生"));
console.log(myArray);
// 替换
console.log(myArray.splice(1, 1, "李先生"));
console.log(myArray);
</script>