從Web開發(fā)到機器學習再到應用程序開發(fā),JavaScript擁有大量的應用程序列表。 幸運的是,JavaScript提供了可以方便使用的全面功能列表,但是,其中許多功能和hack并不流行,很少被談論。 有了如此眾多的應用程序和用例,代碼的復雜性也隨之增加,知道這些開發(fā)技巧的竅門肯定可以為你節(jié)省大量時間。 因此,我整理了9個沒人討論過的實用JavaScript開發(fā)技巧清單,希望對你有所幫助,我們現(xiàn)在開始吧。 1、快速調(diào)整大小和清空數(shù)組編程時我們經(jīng)常需要更改或清空數(shù)組。執(zhí)行此操作的最有效方法是使用Array.length方法。 const array = [1,2,3,4,5]; console.log(array); // 5array.length--; console.log(array); // 4array.length + = 15; console.log(array); // 19 該代碼段的輸出為: [1, 2, 3, 4, 5][1, 2, 3, 4][1, 2, 3, 4, ..15 empty]undefined 你還可以通過將長度設置為0來刪除數(shù)組的所有元素。 let arr= ['a', 'b', 'c'];arr.length = 0;console.log(arr.length); // Ouput=> 0console.log(arr); // Output=> [] 2、有條件的快捷方式 var x=1;if(x==1){console.log(x) }else{console.log("Error") } var x=1;console.log( x==1? x: "Error"); //Output: 1 import defaultExport from "module-name";import { export1 as alias1 } from "module-name";import { export1 , export2 } from "module-name";import { export1 , export2 as alias2 , [...] } from "module-name";import defaultExport, { export1 [ , [...] ] } from "module-name";import defaultExport, * as name from "module-name"; import('some-module') . then(obj => ...). catch(err => console.log(err))
4、空位合并運算符const name = null ?? 'Anonymous';console.log(name); // Output=> 'Anonymous'const age= undefined?? 18;console.log(bar); // Output=> 18 let firstName = null; let lastName = null; let nickName = "Guest"; // shows the first truthy value: alert(firstName || lastName || nickName || "Anonymous"); //Guest 5、合并數(shù)組const array1 = ['a','b','c']; const array2 = ['a','e','f']; const array3 = array1.concat(array2);console.log(array3); //輸出=>數(shù)組[“ a”,“ b”,“ c”,“ a”,“ e”,“ f”] let list1 = ['a', 'b', 'c'];let list2 = ['a', 'e', 'f'];list1.push.apply(list1, list2);console.log(list1);//Output=> Array ["a", "b", "c", "a", "e", "f"] if (var1 !== null || var1 !== undefined || var1 !=='') { var2 = var1;} var2 = var1 || 'Some value'; 7、默認參數(shù)值function calculator(principle,rate,time) {if (principle === undefined) principle = 5000;if (rate === undefined) rate = 6;if (time===undefined) time = 3; ....} function calculator(principle=5000, rate=6, time=3){ ...} 8、in 運算符const car = { make: 'Honda', model: 'Accord', year: 1998 };console.log('make' in car);// expected output: truedelete car.make;if ('make' in car === false) { car.make = 'Suzuki';}console.log(car.make);// expected output: "Suzuki" var q= "onrender" in document.createElement("div");if(q){ ...}else{ ...} function submitName(name) {if(name=== undefined) {throw new Error('Missing parameter'); }return name;} mandatory = () => {throw new Error('Missing parameter');}submitName= (name= mandatory()) => {return name;} 結(jié)論 |
|