11 个JavaScript专业技巧

  1. 使用 XOR 运算符比较数字
    按位异或运算符 (^) 对两个操作数执行按位异或运算。这意味着如果位不同则返回 1,如果相同则返回 0。
const a = 1337;
const b = 69;

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

// pro
a ^ 69 ? console.log('Unequal') : console.log("Equal");    // Unequal
b ^ 69 ? console.log('Unequal') : console.log("Equal");    // Equal
  1. 用数据即时创建和填充数组
// nooby
const array = new Array(3);
for(let i=0; i < array.length; i++){
    array[i] = i;
}

console.log(array)  // [ 0, 1, 2 ]

// pro
const filledArray = new Array(3).fill(null).map((_, i)=> (i));
console.log(filledArray)  // [ 0, 1, 2 ]
  1. 使用对象中的动态属性
// nooby
let propertyName = "body";
let paragraph = {
    id: 1,
};
paragraph[propertyName] = "other stringy";
// { id: 1, body: 'other stringy' }
console.log(paragraph)

// pro
let propertyName = "body";
let paragraph = {
    id: 1,
    [propertyName] : "other stringy"
};
// { id: 1, body: 'other stringy' }
console.log(paragraph)
  1. 轻松消除数组中的重复值

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

// nooby
let answers = [7, 13, 31, 13, 31, 7, 42];
let leftAnswers = [];
let flag = false;
for (i = 0; i< answers.length; i++) {
    for (j = 0; j < leftAnswers.length; j++) {
        if (answers[i] === leftAnswers[j]) {
            flag = true;
        }
    }
    if (flag === false) {
        leftAnswers.push(answers[i]);
    }
    flag = false;
}
//[ 7, 13, 31, 42 ]
console.log(leftAnswers)


// pro
let answers = [7, 13, 31, 13, 31, 7, 42];
let leftAnswers = Array.from(new Set(answers));
// [ 7, 13, 31, 42 ]
console.log(leftAnswers)
  1. 轻松地将对象转换为数组

您可以使用展开运算符将数组转换为对象。

// nooby
let arr = ["v1", "v2", "v3"];
let objFromArray = {};

for (let i = 0; i < arr.length; ++i) {
    if (arr[i] !== undefined) {
        objFromArray[i] = arr[i];
    }
}

// { '0': 'v1', '1': 'v2', '2': 'v3' }
console.log(objFromArray)

// pro
let objFromArrayPro = {...arr};

// { '0': 'v1', '1': 'v2', '2': 'v3' }
console.log(objFromArrayPro)
  1. 使用逻辑运算符进行短路评估

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

const dogs = true;

// nooby
if (dogs) {
    runAway();
}

// pro
dogs && runAway()

function runAway(){
    console.log('You run!');
}
  1. 对象键维护它们的插入顺序

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

const character = {
    name: "Arthas",
    age: 27,
    class: "Paladin",
    profession: "Lichking",
};

// name age class profession
console.log(Object.keys(character));
  1. 创建并填充指定大小的数组

您可以使用带有两个参数的 Array() 构造函数来创建和填充指定大小和值的数组:大小和值,或者对空数组使用 Array.fill() 方法。

// nooby
const size = 5;
const defaultValue = 0;
const arr = []
for(let i = 0; i < size; i++){
    arr.push(defaultValue)
}
console.log(arr);

// pro
const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]
  1. 理解 JavaScript 中的 Truthy 和 Falsy 值

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

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

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

// pro
if(![].length){
    console.log("There is no Array...");
} else {
    console.log("There is an Array, Hooray!");
}

if(!""){
    console.log("There is no content in this string...");
} else {
    console.log("There is content in this string, Hooray!");
}
  1. 用更好的参数改进函数

不要使用单个多个参数,而是使用参数对象。在函数定义中解构它以获得所需的属性。

// nooby
function upload(user, resourceId, auth, files) {}

upload(...); // need to remember the order

// pro
function upload(
    { user, resourceId, auth, files } = {}
) {}

const uploadObj = {
    user: 'me',
    resourceId: uuid(),
    auth: 'token',
    files: []
}

upload(uploadObj);
  1. Null 和 Undefined 在 JavaScript 中是不同的

Null 和 undefined 是两个不同的值,表示没有值。

null => 是的,这是一个值。Undefined 不是

将 null 想象成在一个空盒子前面

把 undefined 想象成在没有盒子的前面

const fnExpression = (s = 'default stringy') => console.log(s);

fnExpression(undefined); // default stringy
fnExpression(); // default stringy

fnExpression(null); // null
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值