JavaScript数组/对象技巧

2020-11-25  本文已影响0人  池鱼_故渊

1.初始化大小为n的数组,并填充默认值

const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]

2.在数组中间插入一些东西

const arr = [1, 2, 3, 4];
const index = 2;
const insertText = "hello";

// 方法1
const result = [...arr.slice(0, index), insertText, ...arr.slice(index)];
console.log(result); // [1, 2, 'hello', 3, 4]

// 方法2
const arrCopy = [...arr]; 
arrCopy.splice(index, 0, insertText); // 参数包括- index、要删除的元素和要添加的新元素
console.log(arrCopy); // [ 1, 2, 'hello', 3, 4 ]

3.从数组中选择随机元素

const themes = ['neo', 'black & white', 'color'];

const randomNumber =  Math.round(Math.random() * 100); // 随机数选择范围 0 - 100
const randomElement = randomNumber % themes.length; // 使数字在数组的范围内
console.log(themes[randomElement]);

4.检查值是否为数组

const arr = [1, 2, 3];
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true

5.从阵列中删除重复项

const array = [1, 1, 2, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];

console.log(uniqueArray); // [1, 2, 3, 5]

6.检查对象是否为空

const obj = {};
console.log(!!obj); // 总是返回true,即使对象是空的

const totalKeys = Object.keys(obj).length; // 返回一个对象中键的总数
console.log(totalKeys ? 'Not Empty' : 'Empty');

7.检查对象中是否存在属性

const obj = {
  test: undefined
};

// 如果属性不存在或值未定义,则无法区分
console.log( obj.test ); // undefined

// the property exists
console.log( "test" in obj ); // true

8.在对象上循环

const age = {
  john: 20,
  max: 43
};

// 方法1
const keys = Object.keys(age);
keys.forEach(key => age[key]++);

console.log(age); // { john: 21, max: 44 }

// 方法2
for(let key in age){
    age[key]++;
}

console.log(age); // { john: 22, max: 45 }

9.防止对象的属性值更新

const obj = {name: 'Codedrops'};
console.log(obj.name); // Codedrops

/* 将'name'键的'writable'描述符设置为false */
Object.defineProperty(obj, 'name', {
        writable: false
});

obj.name = 'ABC';
console.log(obj.name); // Codedrops

10.对象键按插入顺序存储

const obj = {
  name: "Human",
  age: 0,
  address: "Earth",
  profession: "Coder",
};

console.log(Object.keys(obj)); // name, age, address, profession
Objects 保持创建对象的顺序

13 删除数组重复项

var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];


// 方法1
var uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”]
// 方法2
var uniqueFruits2 = […new Set(fruits)];
console.log(uniqueFruits2); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”]

摘自 https://dev.to/318097/10-tricks-on-javascript-arrays-and-objects-3pi

上一篇 下一篇

猜你喜欢

热点阅读