JavaScript 无疑是世界上最酷的语言之一,并且日益流行。所以开发者社区在使用 JS 一段时间后发现了一些技巧和窍门。今天我将与您分享8个技巧和窍门!

1.函数继承

函数继承是通过将扩充函数应用于对象实例来接收特征的过程。该函数提供了一个闭包作用域,您可以使用它来保护某些数据的私密性。扩充功能使用动态对象扩展来扩展具有新属性和方法的对象实例

// Base function
function Drinks(data) {
  var that = {}; // Create an empty object
  that.name = data.name; // Add it a "name" property
  return that; // Return the object
};

// Fuction which inherits from the base function
function Coffee(data) {
  // Create the Drinks object
  var that = Drinks(data);
  // Extend base object
  that.giveName = function() {
    return 'This is ' + that.name;
  };
  return that;
};

// Usage
var firstCoffee = Coffee({ name: 'Cappuccino' });
console.log(firstCoffee.giveName());
// Output: "This is Cappuccino"

2. .map() 替代

.map()还有一个我们可以使用的替代品,它是.from()

let dogs = [
    { name: ‘Rio’, age: 2 },
    { name: ‘Mac’, age: 3 },
    { name: ‘Bruno’, age: 5 },
    { name: ‘Jucas’, age: 10 },
    { name: ‘Furr’, age: 8 },
    { name: ‘Blu’, age: 7 },
]


let dogsNames = Array.from(dogs, ({name}) => name);
console.log(dogsNames); // returns [“Rio”, “Mac”, “Bruno”, “Jucas”, “Furr”, “Blu”]

3. 数字和字符串转换

数字转换为字符串

let num = 4
let newNum = num.toString();

字符串转换为数字

let num = "4"
let stringNumber = Number(num);

快速转换

let num = 15;
let numString = num + ""; // number to string
let stringNum = +s; // string to number

4. 使用长度调整和清空数组

在 javascript 中,我们可以覆盖调用的内置方法length并为其分配我们选择的值

let array_values = [1, 2, 3, 4, 5, 6, 7, 8];  
console.log(array_values.length); 
// 8  
array_values.length = 5;  
console.log(array_values.length); 
// 5  
console.log(array_values); 
// [1, 2, 3, 4, 5]

清空数组

let array_values = [1, 2, 3, 4, 5, 6, 7,8]; 
console.log(array_values.length); 
// 8  
array_values.length = 0;   
console.log(array_values.length); 
// 0 
console.log(array_values); 
// []

5. 用数组解构交换值

该解构赋值语法是JavaScript表达式,使得它可以从阵列解压缩的值,或从属性的对象,为不同的变量。我们还可以使用它来快速交换值,如下所示

let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // result -> 2
console.log(b) // result -> 1

6. 从数组中删除重复项

这个技巧非常简单。比方说,我创建了一个包含数字、字符串和布尔值的数组,但这些值不止一次重复,我想删除重复项。所以我能做的是:

const array = [1, 3, 2, 3, 2, 1, true, false, true, 'Kio', 2, 3];
const filteredArray = [...new Set(array)];
console.log(filteredArray) // [1, 3, 2, true, false, "Kio"]

7. 短 For 循环

您可以为这样的循环编写更少的代码

const names = ["Kio", "Rio", "Mac"];

// Long Version
for (let i = 0; i < names.length; i++) {
  const name = names[i];
  console.log(name);
}

// Short Version
for (let name of names) console.log(name);

8. Performance

在 JS 中,您还可以像 Google 一样获取代码执行的时间

image.png

const firstTime = performance.now();
something();
const secondTime = performance.now();
console.log(`The something function took ${secondTime - firstTime} milliseconds.`);
点赞(0)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部