看过来,这里有JavaScript技术干货?

今天是一篇正经的技术分享,针对JavaScript技能的十来个专业小技巧,如果你想提升一下JS方面的能力成为一个更好的前端开发人员,那么就可以接着看下去哦。

看过来,这里有JavaScript技术干货?_第1张图片

1、使用逻辑运算符进行短路评估

您可以使用逻辑运算符进行短路评估,方法是使用 && 运算符返回表达式链中的第一个假值或最后一个真值,或者使用 || 运算符返回表达式链中的第一个真值或最后一个假值。

1.const dogs = true;

2.

3.

4.// nooby

5.if (dogs) {

6.    runAway();

7.}

8.

9.

10.// pro

11.dogs && runAway()

12.

13.

14.function runAway(){

15.    console.log('You run!');

16.}

2. 对象键维护它们的插入顺序

对象键通过遵循一个简单的规则来维护它们的插入顺序:类整数键按数字升序排序,而非类整数键根据它们的创建时间排序。

1.const character = {

2.    name: "Arthas",

3.    age: 27,

4.    class: "Paladin",

5.    profession: "Lichking",

6.};

7.

8.

9.// name age class profession

10.console.log(Object.keys(character));

3. 理解 JavaScript 中的 Truthy 和 Falsy 值

在布尔上下文中使用时,Truthy 和 Falsy 值会隐式转换为 true 或 false。

虚假值 => false, 0, ""(空字符串), null, undefined, &NaN

真值 => "Values", "0", {}(空对象),&[](空数组)

1.// pro

2.if(![].length){

3.    console.log("There is no Array...");

4.} else {

5.    console.log("There is an Array, Hooray!");

6.}

7.

8.

9.if(!""){

10.    console.log("There is no content in this string...");

11.} else {

12.    console.log("There is content in this string, Hooray!");

13.}

4. 使用 XOR 运算符比较数字

按位异或运算符 (^) 对两个操作数执行按位异或运算。这意味着如果位不同则返回 1,如果相同则返回 0。

1.const a = 1337;

2.const b = 69;

3.

4.

5.// nooby

6.a !== 69 ? console.log('Unequal') : console.log("Equal");  // Unequal

7.b !== 69 ? console.log('Unequal') : console.log("Equal");  // Equal

8.

9.

10.// pro

11.a ^ 69 ? console.log('Unequal') : console.log("Equal");    // Unequal

12.b ^ 69 ? console.log('Unequal') : console.log("Equal");    // Equal

5. 使用对象中的动态属性

1.// nooby

2.let propertyName = "body";

3.let paragraph = {

4.    id: 1,

5.};

6.paragraph[propertyName] = "other stringy";

7.// { id: 1, body: 'other stringy' }

8.console.log(paragraph)

9.

10.

11.// pro

12.let propertyName = "body";

13.let paragraph = {

14.    id: 1,

15.    [propertyName] : "other stringy"

16.};

17.// { id: 1, body: 'other stringy' }

18.console.log(paragraph)

6. 轻松消除数组中的重复值

您可以使用集合消除数组中的重复值。

1.// nooby

2.let answers = [7, 13, 31, 13, 31, 7, 42];

3.let leftAnswers = [];

4.let flag = false;

5.for (i = 0; i< answers.length; i++) {

6.    for (j = 0; j < leftAnswers.length; j++) {

7.        if (answers[i] === leftAnswers[j]) {

8.            flag = true;

9.        }

10.    }

11.    if (flag === false) {

12.        leftAnswers.push(answers[i]);

13.    }

14.    flag = false;

15.}

16.//[ 7, 13, 31, 42 ]

17.console.log(leftAnswers)

18.

19.

20.

21.

22.// pro

23.let answers = [7, 13, 31, 13, 31, 7, 42];

24.let leftAnswers = Array.from(new Set(answers));

25.// [ 7, 13, 31, 42 ]

26.console.log(leftAnswers)

以上是关于JavaScript的一些技巧分享,编写好的代码可以直接用哟。了解更多技术干货可以持续关注我们!

看过来,这里有JavaScript技术干货?_第2张图片

 

 

你可能感兴趣的:(行业专业解析,javascript,前端,java)