实例演示对象字面量的简化、解构赋值与应用场
js 程序
【文章转自国外服务器 http://www.558idc.com处的文章,转载请说明出处】
let arr = ["item1", "item2", "item3"];
let result = arr.forEach((item) => (item = item + " is yours"));
console.log(arr);
let res = arr.map((item) => (item = item + " is yours"));
// forEach没有返回值,
console.log(result);
/**
* map有返回值,且将结果赋值到新的数组中,并没有改变原数组结果
* forEach/map遍历读取集合,操作item似乎不能改变原集合
*/
console.log(res, arr);
// 如果需要改变原数组,采用角标方式来实现
arr.forEach(
(item, index, arr) => (arr[index] = arr[index] + " is yours")
);
arr.map((item, index, arr) => (arr[index] = arr[index] + " or theirs?"));
console.log(arr);
// 如下循环方式实现改变数组值;
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i] + " is yours!";
}
console.log(arr);
arr = ["item4", "item5", "item6"];
// 利用map的返回值特性,以原数组为核心,拼接出需要的元素成为新数组
res = arr.map((item) => `<li><a href="">${item}</a></li>`);
console.log(res);
res = res.join("");
// res = "<ul>" + res + "</ul>";
console.log(res);
document.body.firstElementChild.insertAdjacentHTML("beforeend", res);
/**
* 字面量简化
* 1. 变量的值和名相同,只写变量名
* 2. 方法简化参考匿名函数规则
*/
let pname = "cellphone";
let product = {
pname: pname,
show: function (pname) {
return `Do you have a ${pname}?`;
},
};
console.log(product.show(pname));
pname = "laptop";
product = {
pname,
show: (pname) => `Do you have a ${pname}?`,
};
console.log(product.show(pname));
/**
* 解构赋值
* [] {}为模版标志
* ...剩余参数
*/
let [p1, p2, ...p3] = arr;
console.log(p1, p2, p3);
console.log(p1, p2, ...p3);
[p1, p2, p3, p4 = "itemx"] = arr;
// 一个元素前面加...,会分解开
console.log(p1, p2, p3, ...p4);
// 克隆对象
let products = { name: "camera", price: 1000, storage: 100 };
let { ...camera } = products;
console.log(camera);
console.log(camera.name);
// 解构传参
products = { name: "fridge", price: 2000, storage: 10 };
let { ...fridge } = products;
function show(products) {
console.log(`${products.name}'s price is ${products.price}`);
}
show(fridge);
show({ name: "computer", price: 3000 });