1、es6解构-展开-键值相同

  1. <script>
  2. var arr = [
  3. {
  4. name:"lisi",
  5. age:18,
  6. likes:["lol","足球"],
  7. alikes:["音乐","电影"],
  8. sex:"male"
  9. },
  10. {
  11. name:"王五",
  12. age:17,
  13. likes:["al","栏球"],
  14. alikes:["防抖","放到"],
  15. sex:"male"
  16. },
  17. {
  18. name:"张三",
  19. age:165,
  20. likes:["发顺丰","jf"],
  21. alikes:["音乐9","10电影"],
  22. sex:"male"
  23. }
  24. ]
  25. var res = [];
  26. for(var i=0;i<arr.length;i++){
  27. /* 解构 */
  28. var {name,age,likes,alikes} = arr[i];
  29. /* 展开 */
  30. likes.push(...alikes);
  31. /* 键和值相同只用写一个 */
  32. var obj ={
  33. name,
  34. age,
  35. likes
  36. }
  37. res.push(obj);
  38. }
  39. console.log(res)
  40. </script>

2.让数组中被搜索的值,至于顶部

  1. <script>
  2. /* 让数组中被搜索的值,至于顶部 */
  3. var arr= ["html","css","js","vue","react"]
  4. /* ["js","html","css","vue","react"] */
  5. $("#app").keyup( function(event){
  6. if(event.keyCode==13){
  7. var value = $(this).val();
  8. if(arr.indexOf(value)!=-1){
  9. console.log(value)
  10. var index = arr.indexOf(value);
  11. arr.splice(index,1);
  12. arr.unshift(value);
  13. console.log(arr);
  14. }
  15. }
  16. })
  17. </script>

3.历史搜索

  1. <script>
  2. /* 1、获取输入框的值 */
  3. var historys = [];
  4. $("#app").keyup(function (event) {
  5. if (event.keyCode == 13) {
  6. /* 2.将值添加到一个数组里面去 */
  7. var value = $(this).val();
  8. var template = `
  9. <button>${value}</button>
  10. `
  11. /* 只有数组中不包含输入的关键字才向数组添加 */
  12. if (value) {
  13. if (!historys.includes(value)) {
  14. historys.unshift(value);
  15. /* 3、渲染数据到页面 */
  16. $("#container").prepend(template)
  17. $(this).val("")
  18. } else {
  19. var index = historys.indexOf(value);
  20. var res = historys.splice(index, 1);
  21. historys.unshift(...res);
  22. console.log(historys)
  23. $("button").eq(index).remove();
  24. $("#container").prepend(template)
  25. $(this).val("")
  26. }
  27. }
  28. }
  29. })
  30. </script>