源码学习 第36期 | omit.js 剔除对象中的属性

100 阅读2分钟

源码:

function omit(obj, fields) {
    // eslint-disable-next-line prefer-object-spread
    const shallowCopy = Object.assign({}, obj);
    for (let i = 0; i < fields.length; i += 1) {
      const key = fields[i];
      delete shallowCopy[key];
    }
    return shallowCopy;
  }
  
  export default omit;

这个函数的操作就是浅拷贝一个对象,并删除指定的属性

关于浅拷贝、深拷贝的区别,浅拷贝就是des复制src这个对象,如果src的属性是引用类型值,那么des复制的也是引用类型值,这个引用指向同一个对象,这个对象的变化会同时反映在src和des中; 而深拷贝则是创建一个新的对象,虽然这个对象的内容和src中的那个对象完全一样,但却是不同的引用,指向“不同的”对象,这样一来这两个对象的变更就是互不影响的了。

测试用例:

import assert from 'assert';
import omit from '../src';

describe('omit', () => {
  it('should create a shallow copy', () => {
    const benjy = { name: 'Benjy' };
    const copy = omit(benjy, []);
    // 比较copy, benjy中各键值对的值是否相等
    assert.deepEqual(copy, benjy);
    // 相当于copy == benjy 这是两个对象所以不等
    assert.notEqual(copy, benjy);
  });

  it('should drop fields which are passed in', () => {
    const benjy = { name: 'Benjy', age: 18 };
    assert.deepEqual(omit(benjy, ['age']), { name: 'Benjy' });
    assert.deepEqual(omit(benjy, ['name', 'age']), {});
  });
});
  • assert.deepEqual() 用来比较两个对象,只要他们的属性一一对应,且值都相等,就认为两个对象相等。
  • assert.notEqual() 实际值不等于预期值时,pass;实际值等于预期值时,报错

package.json文件:

node es/demo.js 执行这个命令来调试的时候,控制台报错

SyntaxError: Cannot use import statement outside a module

Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

就需要在package.json文件中设置"type": "module",或者把es目录下的两个js文件扩展名改成.mjs,然后就可以单步调试了。

以下摘自Node.js文档

The "type" field defines the module format that Node.js uses for all .js files that have that package.json file as their nearest parent.

Files ending with .js are loaded as ES modules when the nearest parent package.json file contains a top-level field "type" with a value of "module".

If the nearest parent package.json lacks a "type" field, or contains "type": "commonjs".js files are treated as CommonJS. If the volume root is reached and no package.json is found, .js files are treated as CommonJS.

The nearest parent package.json is defined as the first package.json found when searching in the current folder, that folder's parent, and so on up until a node_modules folder or the volume root is reached.

Regardless of the value of the "type" field, .mjs files are always treated as ES modules and .cjs files are always treated as CommonJS.

总结:

  • 复习了深浅拷贝的区别
  • 了解了单步调试及assert断言测试
  • 了解了package.json文件的各属性,尤其是type属性(有一个很像的types属性)以及esm和commonjs的区别