关于一些JavaScript的小技巧,转载自https://www.geekjc.com/post/5a0a8c9a592e38541f7703c8。
1if语句可以简写三目运算:
const x = 20;let answer; if (x > 10) { answer = ‘greater than 10‘; } else { answer = ‘less than 10‘; }
const answer = x > 10 ? ‘greater than 10‘ : ‘less than 10‘;
2.字符串拼接:
var arr = [{ "name":"大春哥", "age":20, "sex":"男" }]; for (let i = 0;i<arr.length;i++) { console.log("名字:"+ arr[i].name + "年龄:"+ arr[i].age + "性别:"+ arr[i].sex); } // es6字符串拼接: for (let i = 0;i<arr.length;i++) { console.log(`名字:${arr[i].name} 年龄:${arr[i].age} 性别:${arr[i].sex}`); } //注:在` `写变量,ESC键下面英文状态可以按出` `
3.箭头函数
function sayHello(name) { console.log(‘Hello‘, name); } setTimeout(function() { console.log(‘Loaded‘) }, 2000); list.forEach(function(item) { console.log(item); }); // 用箭头函数简写: sayHello = name => console.log(‘Hello‘, name); setTimeout(() => console.log(‘Loaded‘), 2000); list.forEach(item => console.log(item));
4,数组去重(划重点QAQ 面试题好几次都有这个)
var arr = [1, 1, 2, 2, 3, 3]; function unique(arr){ let res = []; for (var i = 0;i<arr.length;i++) { for (var j = 0; j<res.length;j++) { if (arr[i] === res[j]) { break; } } if (j === res.length) { res.push(arr[i]); } } return res; } console.log(unique(arr)); //es6 Set方法 function unique(arr){ return Array.from(new Set(arr)); } console.log("es6Set方法:",unique(arr));
时间: 2024-11-08 06:16:46