在JavaScript世界里,有些操作会让你无法理解,但是却无比优雅!
var obj; if(obj instanceof Object){ console.log(obj.a); }else{ console.log('对象不存在'); }
ES6中有简便写法,可以帮我们简短代码,从而更加明确
var obj; console.log(obj?.a || '对象不存在');
var list=[1,2,3,4,5,6,7,8,9,10,11,12,13]; list=list.map(ele=>('0' + ele).slice(-2)); console.log(list);
var obj = { name: 'Jack' }; console.table(obj); obj.name= 'Rose'; console.table(obj);
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(array.slice(-1)); // Result: [9] console.log(array.slice(-2)); // Result: [8, 9] console.log(array.slice(-3)); // Result: [7, 8, 9]
let name = "Charlse" let place = "India"; let isPrime = bit =>{ return (bit === 'P'? 'Prime' : 'Nom-Prime') } let messageConcat = `Mr.name' is form ${place} .He is a ${isPrime('P')} member`;
<input id="btn1" type="button" value="点我" onclick="test();" /> <script> function test() { const sos = `阿尤!不错哦`; const synth = window.speechSynthesis; let msg = new SpeechSynthesisUtterance(sos); synth.speak(msg) } </script>
然后点击按钮,就会触发test方法的执行实现语音合成
这里推荐使用Chrome浏览器,因为HTML5的支持度不同
let floatNum = 100.5; let intNum = ~~floatNum; console.log(intNum); // 100
let str="10000"; let num = +str; console.log(num); // 10000
let obj = { key1: "value1", key2: "value2" }; let revert = {}; Object.entries(obj).forEach(([key, value]) => revert[value] = key); console.log(revert);
let arrNum = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ]; let arrString = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" ]; let arrMixed = [ 1, "1", "2", true, false, false, 1, 2, "2" ]; arrNum = Array.from(new Set(arrNum)); arrString = [...new Set(arrString)]; arrMixed = [...new Set(arrMixed)]; console.log(arrNum); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] console.log(arrString); // ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] console.log(arrMixed); // [1, "1", "2", true, false, 2]
const arr = [1,2,3] const obj = {...arr} console.log(obj)
const obj1 = { a: 1 } const obj2 = { b: 2 } const combinObj = { ...obj1, ...obj2 } console.log(combinObj)
也就是通过展开操作符(spread operator)来实现。
let arr = [0, 1, 2, 3, 4, 5]; const last = arr.slice(-1)[0]; console.log(last);
var sca = function() { console.log('msg')//永远只会执行一次 sca = function() { console.log('foo') } } sca() // msg sca() // foo sca()
提高工作效率,减少代码量,降低键盘磨损程度
我希望你喜欢它并学到了一些新东西。
感谢你的阅读,编程快乐!
.