Blogger Information
Blog 18
fans 0
comment 0
visits 7926
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
字符串,数组api实例演示
只如初见
Original
543 people have browsed it

字符串

  1. <script>
  2. // 创建字符串
  3. let string = '我是字符串';
  4. // 长度
  5. console.log(string.length);
  6. //根据索引获取字符串
  7. console.log(string[1]);
  8. console.log(string.charAt(2));
  9. // 查询字符串索引
  10. console.log(string.indexOf('字'));
  11. console.log(string.search('字'));
  12. // 字符串连接
  13. console.log(string + 'baidu.com');
  14. console.log(`${string}baidu.com`);
  15. // 字符串替换
  16. console.log(string.replace('中文网', '.cn'));
  17. // 取子串
  18. // slice 取子串,忽略结束索引对应的值
  19. console.log(string.slice(0, 3));
  20. // substr: 不知到哪结束,但是知道取多少
  21. console.log(string.substr(0, 3));
  22. // 字符串转数组
  23. let s = '1-2-3-4-5';
  24. console.log(s.split('-'));
  25. console.log(string.split('', 4));
  26. // 大小写转换
  27. // toLowerCase,toUpperCase
  28. console.log(string.toUpperCase());
  29. // html标签相关
  30. console.log(string.link('https://baidu.com'));
  31. document.body.insertAdjacentHTML('afterbegin', string.link('https://baidu.com'));
  32. </script>

数组api

  1. // 遍历数组
  2. // 1. forEach,map
  3. // 2. every, some
  4. // 3. filter, find, findIndex
  5. // 4. reduce
  6. let arr = [1, 2, 3, 4, 5];
  7. // arr.forEach(function(元素的值,值对应的索引,数组本身) {
  8. // 对数组中的每个元素逐个调用回调方式进行处理
  9. // })
  10. let res = arr.forEach((item, index, arr) => console.log(item, index, arr));
  11. // 需要返回值,就用map
  12. res = arr.map((item, index, arr) => [item, index, arr]);
  13. // every, some
  14. // every: 数组成员全部满足条件,则返回 true , 否则 false 与
  15. console.log(arr.every(item => item >= 0));
  16. console.log(arr.some(item => item >= 6));
  17. // filter,只返回为真的元素组成的数组
  18. console.log(arr.filter(item => item >= 3));
  19. // find,返回满足条件的第一个
  20. // arr.filter(item => item >= 3)[0]
  21. console.log(arr.find(item => item >= 3));
  22. // 归并 reduce
  23. // arr.reduce(function(累加器,元素的值,值对应的索引,数组本身) {})
  24. res = arr.reduce(function (acc, item, index, arr) {
  25. console.log(`acc=${acc}, item=${item}`);
  26. return acc + item;
  27. }, 1000);
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post