nodejs 常用语法

合并objects

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, 注意目标对象自身也会改变。

const

const定义的变量无法修改;
const b = 2;
b = 5; //会报错

let,是块级作用域

let c = 3;
console.log('函数外let定义c:' + c);//输出c=3
function change(){
let c = 6;
console.log('函数内let定义c:' + c);//输出c=6
} 
change();
console.log('函数调用后let定义c不受函数内部定义影响:' + c);//输出c=3

||

data = {'a':1,'b':2}
x =  data.c || 1
console.log(x);//x=1

Object.keys

返回map的key组成的数据
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // ['2', '7', '100']

map()

map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
let numbers = [1, 5, 10, 15];
let doubles = numbers.map((x) => {
   return x * 2;
});

// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]

const list = res.map((o) => {
  if (o.params) {
    o.params = this.encryptService.decrypt(o.params);
  }
  return o;
});
const x = {'name':'jwen','age':28}

const {name: Name} =x

//Name='jwen'

Reflect.deleteProperty() 

var obj = { x: 1, y: 2 };
Reflect.deleteProperty(obj, "x"); // true
obj; // { y: 2 }

var arr = [1, 2, 3, 4, 5];
Reflect.deleteProperty(arr, "3"); // true
arr; // [1, 2, 3, , 5]

// 如果属性不存在,返回 true
Reflect.deleteProperty({}, "foo"); // true

// 如果属性不可配置,返回 false
Reflect.deleteProperty(Object.freeze({foo: 1}), "foo"); // false

filter

const userCounts = userList.filter((e) => e.isDelete === false);

//去重
 let r = [];
    const array = [
      'apple',
      'strawberry',
      'banana',
      'pear',
      'apple',
      'orange',
      'orange',
      'strawberry'
    ];
    r = array.filter(function(element, index, self) {
      return self.indexOf(element) === index;
    });
    return r;

遍历对象属性

    const arr = Object.keys(data).map((key) => ({
      Name: key,
      Value: data[key],
    }));

 

参考文档:

https://www.cnblogs.com/jwentest/p/7218536.html

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty

posted @ 2023-02-23 09:10  PrintY  阅读(144)  评论(0编辑  收藏  举报