我最喜欢的JavaScript技巧

问候。我提请您注意Tapas Adhikary于2020年7月28日发表的文章“我最喜欢的JavaScript技巧和窍门”的翻译





大多数编程语言都足够开放,以使开发人员能够以不同的方式完成相同的事情。JavaScript也不例外。通常,我们有不同的方法来获得相同的结果,有时甚至会造成混淆。



, . . , - .



1. , ()



"+" – . , ( ) .



let name = 'Charlse';
let place = 'India';
let isPrime = bit => {
  return (bit === 'P' ? 'Prime' : 'Nom-Prime');
}

//      "+"
let messageConcat = 'Mr. ' + name + ' is from ' + place + '. He is a' + ' ' + isPrime('P') + ' member.'


( ) . , (``). . . , ${}.



:



let name = 'Charlse';
let place = 'India';
let isPrime = bit => {
  return (bit === 'P' ? 'Prime' : 'Nom-Prime');
}

//   
let messageTemplateStr = `Mr. ${name} is from ${place}. He is a ${isPrime('P')} member.`
console.log(messageTemplateStr);


2. isInteger



, . JavaScript API "Number" "isInteger()". , .



let mynum = 123;
let mynumStr = "123";

console.log(`${mynum} is a number?`, Number.isInteger(mynum));
console.log(`${mynumStr} is a number?`, Number.isInteger(mynumStr));


:





3.



- , "event.target.value" , "input" "number"?



. , , , , .



<input type='number' onkeyup="trackChange(event)" />


"event.target.value". . - . , ( 16.56)? "parseFloat()"? - !



function trackChange(event) {
   let value = event.target.value;
   console.log(`is ${value} a number?`, Number.isInteger(value));
}


, "event.target.valueAsNumber".



let valueAsNumber = event.target.valueAsNumber;
console.log(`is ${value} a number?`, Number.isInteger(valueAsNumber));




4. AND



, .



let isPrime = true;
const startWatching = () => {
    console.log('Started Watching!');
}


.



if (isPrime) {
    startWatching();
}


AND (&&)? , "if" . , ?



isPrime && startWatching();


5. OR



, OR.



let person = {name: 'Jack'};

//   "age"  "undefined",   35
let age = person.age || 35;

console.log(`Age of ${person.name} is ${age}`);


6.



– , . .





let planets = ['Mercury ', 'Mars', 'Venus', 'Earth', 'Neptune', 'Uranus', 'Saturn', 'Jupiter'];
let randomPlanet = planets[Math.floor(Math.random() * planets.length)];
console.log('Random Planet', randomPlanet);




 let getRandom = (min, max) => {
     return Math.round(Math.random() * (max - min) + min);
 }
 console.log('Get random', getRandom(0, 10));




learn.javascript.ru, , 2 , . .


7.



JavaScript . . "undefined", .



. "message" "greetings" "Hello".



let greetings = (name, message='Hello,') => {
    return `${message} ${name}`;
}

console.log(greetings('Jack'));
console.log(greetings('Jack', 'Hola!'));


8.



, .



,



let isRequired = () => {
    throw new Error('This is a mandatory parameter.');
}


, . , "undefined", , .



let greetings = (name=isRequired(), message='Hello,') => {
    return `${message} ${name}`;
}
console.log(greetings());


"name" "undefined", - , "isRequired()". :





9. ""



, , .



JavaScript .



let count = 1;
let ret = (count++, count);
console.log(ret);


"ret" 2. , 32.



let val = (12, 32);
console.log(val);


? ? "for".



"j" "i".



for (var i = 0, j = 50; i <= 50; i++, j--)


10.



, , . "..." (, ).



:



let emp = {
 'id': 'E_01',
 'name': 'Jack',
 'age': 32,
 'addr': 'India'
};

let job = {
 'title': 'Software Dev',
  'location': 'Paris'
};


spread- ( ):



 // spread-
 let merged = {...emp, ...job};
 console.log('Spread merged', merged);


. "Object.assign()":



 console.log('Object assign', Object.assign({}, emp, job));


:





, spread- "Object.assign" (shallow) . , , .



, , , lodash



11.



– , .









, :\



let [fire, clock, , watermelon] = emojis;


, "let fire = emojis[0];", . , "", ? , ?



console.log(fire, clock, watermelon);


:





, "rest". , , , "...rest", .



let [fruit, ...rest] = emojis;
console.log(rest);


:







,



let shape = {
  name: 'rect',
  sides: 4,
  height: 300,
  width: 500
};


, , .



let {name, sides, ...restObj} = shape;
console.log(name, sides);
console.log(restObj);






.



12.



, ,



let fire = '';
let fruit = '';

[fruit, fire] = [fire, fruit];
console.log(fire, fruit);


13. isArray



, ,



let emojis = ['', '️', '', ''];
console.log(Array.isArray(emojis));

let obj = {};
console.log(Array.isArray(obj));


14."'undefined" "null"



"undefined" – , ,

"null" – ,



"undefined" "null"



undefined === null // false




15. url-



"window.location" . , , , url- .



,



window.location.search


search属性返回网址字符串中问号“ ?project=js之后的部分



要获取查询参数,除了“ location.search”之外,您还可以使用另一个有用的API,称为“ URLSearchParams”。



let project = new URLSearchParams(location.search).get('project');


结果,我们得到“ js



在此处阅读有关此主题的更多信息



这不是结束



还有许多其他有用的技术。当我遇到它们时,我决定将它们和一些小示例一起添加到存储库中。



您最喜欢的JavaScript技巧是什么?在下面的评论中分享它们如何?




All Articles