JS 语句语法3 vue1

21.案例-城市天气检索.js

javascript 复制代码
// 1. 先自动定位城市
let currentCity = "";
function autoLocation() {
  axios({
    url: "https://restapi.amap.com/v3/ip",
    method: "GET",
    params: {
      key: "e45ba07980d4a0817d2edeba0de23add",
    },
  }).then((data) => {
    currentCity = data.data.city;
    document.getElementById("city").innerText = `当前城市: ${currentCity}`;
    // 2. 根据城市查询天气, 获取经纬度坐标
    getWeather(currentCity);
    getGeolocation(currentCity);
  });
}
autoLocation();

// 封装查询天气得函数: 自动定位城市和用户输入城市都需要调用
function getWeather(city) {
  axios({
    url: "https://restapi.amap.com/v3/weather/weatherInfo",
    method: "GET",
    params: {
      key: "e45ba07980d4a0817d2edeba0de23add",
      city: city,
    },
  }).then((data) => {
    // console.log(data.data.lives[0]);
    // const city = data.data.city;
    document.getElementById("wea").innerText = `当前城市天气: ${JSON.stringify(
      data.data.lives[0]
    )}`;
  });
}

// 查询按钮点击事件
function searchCity() {
  const inp = document.getElementById("searchCity");
  if (inp.value) {
    getWeather(inp.value);
    getGeolocation(inp.value);
  } else alert("缺少关键字");
}

// 封装获取经纬度坐标得函数
function getGeolocation(city) {
  axios({
    url: "https://restapi.amap.com/v3/geocode/geo",
    method: "GET",
    params: {
      key: "e45ba07980d4a0817d2edeba0de23add",
      address: city,
    },
  }).then((data) => {
    // console.log(data.data.geocodes[0].location);
    document.getElementById(
      "geo"
    ).innerText = `经纬度坐标: ${data.data.geocodes[0].location}`;
  });
}

// 检索周边信息
function poi() {
  const inp = document.getElementById("poi");
  if (inp.value) {
    axios({
      url: "https://restapi.amap.com/v3/place/text",
      method: "GET",
      params: {
        key: "e45ba07980d4a0817d2edeba0de23add",
        keywords: inp.value,
        city: currentCity,
      },
    }).then((data) => {
      console.log(data.data);
      // document.getElementById(
      //   "geo"
      // ).innerText = `经纬度坐标: ${data.data.geocodes[0].location}`;
    });
  } else alert("缺少关键字");
}

22.案例-数组练习.js

javascript 复制代码
// 第一题: 通过forEach实现数字3~8相加的和; 3+4+5+...+8
const arr = [3, 4, 5, 6, 7, 8];
let num = 0;
arr.forEach((val) => (num += val));
console.log(num);

// 第二题: 从一个歌手数组中, 根据用户输入的歌手名称, 输出该歌手所有的歌曲
const singerArr = [
  { singer: "周杰伦", musics: ["青花瓷1", "千里之外1"] },
  { singer: "林俊杰", musics: ["青花瓷2", "千里之外2"] },
];
// const singer = prompt("输入歌手名称:");
// singerArr.forEach((item) => {
//   if (item.singer == singer) console.log(item.musics);
//   else console.log("不存在");
// });

// const result = singerArr.find((item) => {
//   return item.singer == singer;
// });
// if (result) console.log(result.musics);
// else console.log("不存在");

// const result = singerArr.findIndex((item) => item.singer == singer);
// if (result != -1) console.log(singerArr[result].musics);
// else console.log("不存在");

// const result = singerArr.filter((item) => item.singer == singer);
// if (result.length != 0) console.log(result[0].musics);
// else console.log("不存在");

// 第三题: 通过让用户输入索引以及数据的方式, 向数组指定位置添加Object元素, 要求可以连续添加多个用户信息, 当用户输入 "结束" 时, 停止添加操作.
let isStart = true;
const users = [];
while (isStart) {
  var index = prompt("请输入索引(不想添加输入结束): ");
  if (index == "结束") {
    isStart = false;
    break;
  }
  var uname = prompt("请输入姓名: ");
  var uage = prompt("请输入年龄: ");
  users.splice(index, 0, { name: uname, age: uage, id: index });
  console.log(users);
}

23.es6语法汇总.js

javascript 复制代码
// 展开运算符: 数组, 对象都可以用.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const arr3 = [...arr1, ...arr2];
const arr4 = [...arr2, ...arr1];
console.log(arr3, arr4);

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3 };
console.log({ ...obj1, ...obj2 });

// 对象简写: 当对象中键和值名称相同时, 不用写 "键:值", 直接写一个变量.
const uname = "小名";
const uage = 20;

const user = {
  uname, // 等价于 uname:uname
  uage,
  usex: true,
};
console.log(user);

24.Promise对象.js

javascript 复制代码
// Promise是异步编程解决方案, 专门解决异步编程中得各种问题.
// 1. 封装请求函数时, 如何在函数调用时, 得到请求结果.
// 2. 回调地狱问题: 当多个异步任务要按顺序执行时(通常是下一个任务要用到上一个任务得结果), 会出现异步任务得层层嵌套, 当嵌套得层数过多时, 就出现了回调地狱. 回调地狱不是语法错误, 只是代码不好管理了, 不好维护了.

// 通过axios配置公共接口域名
axios.defaults.baseURL = "https://restapi.amap.com/v3";

// 封装axios请求, 为了使用方便, 不用到处写axios代码了
function http(url, params = {}, method = "GET", data = {}) {
  // 每一次调用http方法, 都会返回一个新得Promise对象, 同时执行Promise中得异步任务
  const paramsObj = {
    key: "e45ba07980d4a0817d2edeba0de23add",
    ...params,
  };
  return new Promise((resolve, reject) => {
    axios({
      url,
      method,
      params: paramsObj, // GET/DELETE参数,
      data, // POST/PUT参数, axios会把data里面得参数放在请求体. http协议规定发请求必须有请求头, 请求行, 请求体. 浏览器默认会生成这三项内容.
    })
      .then(({ data }) => {
        console.log(`Promise任务成功: ${url}`);
        resolve(data); // 在Promise内部调用resolve表明Promise任务结束. 通过它向外传递参数.
      })
      .catch((error) => {
        // console.log("----", error);
        reject("Error"); // 在Promise内部调用reject表明Promise任务非正常原因结束. 通过它向外传递参数.
      });
  });
}

// 1. 先自动定位城市
let currentCity = "";
async function autoLocation() {
  // await: 关键字, 表示等待得含义, 用于修饰promise对象, 且它后面只能跟Promise对象. 它可以让线程等待某个异步任务执行结束之后, 再执行其他异步任务.
  // await只能在有async修饰得函数中使用, 不能单独使用. 经过await修饰得Promise, resolve返回得结果, 直接用变量接收, 不需要使用.then了, 进一步简化了代码. await无法取代.catch()
  try {
    await http("/ip");
  } catch (error) {
    console.log("======", error);
  }

  http("/ip123").catch((error) => {
    console.log("error", error);
  });

  // const weaResp = await http("/weather/weatherInfo", {
  //   city: cityResp.city,
  // });
  // http("/ip123").catch((res) => {
  //   console.log("+++++++", res);
  // });

  /*
  http("https://restapi.amap.com/v3/ip", "GET", {
    key: "e45ba07980d4a0817d2edeba0de23add",
  }).then(({city}) => {
    console.log("城市: ", city);
    // .then()中得形参, 接收得就是resolve()得实参
    // 2. 根据定位城市查询天气和经纬度
    http("https://restapi.amap.com/v3/weather/weatherInfo", "GET", {
      key: "e45ba07980d4a0817d2edeba0de23add",
      city,
    }).then((weather) => {
      console.log("天气: ", weather);
      // 3. 根据天气情况推荐衣物, 出行工具等出行建议
      http("出行建议接口", "GET", {
        key: "e45ba07980d4a0817d2edeba0de23add",
        address: city,
      }).then((loc) => {
        console.log("经纬度: ", loc);
      });
    });
    http("https://restapi.amap.com/v3/geocode/geo", "GET", {
      key: "e45ba07980d4a0817d2edeba0de23add",
      address: city,
    }).then((loc) => {
      console.log("经纬度: ", loc);
    });
  });
  */
}
autoLocation();

25.对象解构赋值.js

javascript 复制代码
import sumFun from "./http.js"; // 从 http.js 模块导入 sum 函数, 会自动找export default
import { a1, b1 } from "./http.js"; // 从 http.js 模块按需导入, 必须使用{}, 导入的变量名必须和导出的变量名保持一致.
import { a1 as aa, b1 as bb } from "./http.js"; // 使用as起别名
import * as http from "./http.js"; // 通过*一次导入所有模块内容, 为了方便使用通过as起别名

console.log(
  "模块: ",
  sumFun(10, 20),
  a1,
  b1,
  aa,
  bb,
  http.a1,
  http.b1,
  http.sum(100, 200)
);
const user = {
  city: "郑州市",
  other: {
    address: "高新区",
    a: 100,
    b: 200,
  },
};

const city = "北京";
// es6解构赋值: 解构的属性名必须和对象中属性保持一致.
const {
  city: ucity, // 起别名
  other: { address, a, b }, // 深度解构
} = user;
console.log(ucity, address, a, b);

// 1. 深度解构; 2. 解构的属性设置别名; 3. 解构的属性名必须和对象中的属性名保持一致;

function test({ a, b, c: { d } }) {
  console.log("====", a, b, d);
}
test({ a: 1, b: 2, c: { d: 3 } });
相关推荐
AI原吾1 小时前
掌握Python-uinput:打造你的输入设备控制大师
开发语言·python·apython-uinput
机器视觉知识推荐、就业指导1 小时前
Qt/C++事件过滤器与控件响应重写的使用、场景的不同
开发语言·数据库·c++·qt
毕设木哥1 小时前
25届计算机专业毕设选题推荐-基于python的二手电子设备交易平台【源码+文档+讲解】
开发语言·python·计算机·django·毕业设计·课程设计·毕设
珞瑜·1 小时前
Matlab R2024B软件安装教程
开发语言·matlab
weixin_455446171 小时前
Python学习的主要知识框架
开发语言·python·学习
孤寂大仙v1 小时前
【C++】STL----list常见用法
开发语言·c++·list
她似晚风般温柔7892 小时前
Uniapp + Vue3 + Vite +Uview + Pinia 分商家实现购物车功能(最新附源码保姆级)
开发语言·javascript·uni-app
咩咩大主教2 小时前
C++基于select和epoll的TCP服务器
linux·服务器·c语言·开发语言·c++·tcp/ip·io多路复用
FuLLovers2 小时前
2024-09-13 冯诺依曼体系结构 OS管理 进程
linux·开发语言
Jiaberrr3 小时前
前端实战:使用JS和Canvas实现运算图形验证码(uniapp、微信小程序同样可用)
前端·javascript·vue.js·微信小程序·uni-app