Blogger Information
Blog 12
fans 0
comment 0
visits 3524
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示对象字面量的简化、解构赋值与应用场景(克隆与传参)
len
Original
189 people have browsed it

js 程序

  1. let arr = ["item1", "item2", "item3"];
  2. let result = arr.forEach((item) => (item = item + " is yours"));
  3. console.log(arr);
  4. let res = arr.map((item) => (item = item + " is yours"));
  5. // forEach没有返回值,
  6. console.log(result);
  7. /**
  8. * map有返回值,且将结果赋值到新的数组中,并没有改变原数组结果
  9. * forEach/map遍历读取集合,操作item似乎不能改变原集合
  10. */
  11. console.log(res, arr);
  12. // 如果需要改变原数组,采用角标方式来实现
  13. arr.forEach(
  14. (item, index, arr) => (arr[index] = arr[index] + " is yours")
  15. );
  16. arr.map((item, index, arr) => (arr[index] = arr[index] + " or theirs?"));
  17. console.log(arr);
  18. // 如下循环方式实现改变数组值;
  19. for (let i = 0; i < arr.length; i++) {
  20. arr[i] = arr[i] + " is yours!";
  21. }
  22. console.log(arr);
  23. arr = ["item4", "item5", "item6"];
  24. // 利用map的返回值特性,以原数组为核心,拼接出需要的元素成为新数组
  25. res = arr.map((item) => `<li><a href="">${item}</a></li>`);
  26. console.log(res);
  27. res = res.join("");
  28. // res = "<ul>" + res + "</ul>";
  29. console.log(res);
  30. document.body.firstElementChild.insertAdjacentHTML("beforeend", res);
  31. /**
  32. * 字面量简化
  33. * 1. 变量的值和名相同,只写变量名
  34. * 2. 方法简化参考匿名函数规则
  35. */
  36. let pname = "cellphone";
  37. let product = {
  38. pname: pname,
  39. show: function (pname) {
  40. return `Do you have a ${pname}?`;
  41. },
  42. };
  43. console.log(product.show(pname));
  44. pname = "laptop";
  45. product = {
  46. pname,
  47. show: (pname) => `Do you have a ${pname}?`,
  48. };
  49. console.log(product.show(pname));
  50. /**
  51. * 解构赋值
  52. * [] {}为模版标志
  53. * ...剩余参数
  54. */
  55. let [p1, p2, ...p3] = arr;
  56. console.log(p1, p2, p3);
  57. console.log(p1, p2, ...p3);
  58. [p1, p2, p3, p4 = "itemx"] = arr;
  59. // 一个元素前面加...,会分解开
  60. console.log(p1, p2, p3, ...p4);
  61. // 克隆对象
  62. let products = { name: "camera", price: 1000, storage: 100 };
  63. let { ...camera } = products;
  64. console.log(camera);
  65. console.log(camera.name);
  66. // 解构传参
  67. products = { name: "fridge", price: 2000, storage: 10 };
  68. let { ...fridge } = products;
  69. function show(products) {
  70. console.log(`${products.name}'s price is ${products.price}`);
  71. }
  72. show(fridge);
  73. show({ name: "computer", price: 3000 });
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