loadash知识整理

发布于:2025-03-10 ⋅ 阅读:(21) ⋅ 点赞:(0)

1、_.isPlainObject(value)

参数
1. `value` _(*)_: 要检查的值。
返回
_(boolean)_: 如果 `value` 为一个普通对象,那么返回 `true`,否则返回 `false`。
例子
```plain

function Foo() {
this.a = 1;
}
_.isPlainObject(new Foo);
// => false
_.isPlainObject([1, 2, 3]);
// => false
_.isPlainObject({ ‘x’: 0, ‘y’: 0 });
// => true
_.isPlainObject(Object.create(null));
// => true


<h4 id="PuQ5L">相似函数:`_.isObject(value)`</h4>
<font style="color:#1C1E21;">检查 </font>`value`<font style="color:#1C1E21;"> 是否为 </font>`Object`<font style="color:#1C1E21;"> 的</font>[language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types)<font style="color:#1C1E21;">。 </font>_(例如: arrays, functions, objects, regexes,_`_new Number(0)_`_, 以及 _`_new String('')_`_)_

<h4 id="bqOJk">参数</h4>
1. `value` _(*)_: 要检查的值。

<h4 id="TBgWw">返回</h4>
_(boolean)_: 如果 `value` 为一个对象,那么返回 `true`,否则返回 `false`。

<h4 id="PwwxS">例子</h4>
```plain
_.isObject({});
// => true
 
_.isObject([1, 2, 3]);
// => true
 
_.isObject(_.noop);
// => true
 
_.isObject(null);
// => false

2、_.get(object, path, [defaultValue])

根据 `object` 对象的`path` 路径获取值。 如果解析 value 是 `undefined`  会以 `defaultValue`  取代。
参数
1. `object` _(Object)_: 要检索的对象。 2. `path` _(Array|string)_: 要获取属性的路径。 3. `[defaultValue]` _(*)_: 如果解析值是 `undefined` ,这值会被返回。
返回
_(*)_: 返回解析的值。
例子
```plain var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.get(object, 'a[0].b.c'); // => 3 _.get(object, ['a', '0', 'b', 'c']); // => 3 _.get(object, 'a.b.c', 'default'); // => 'default' ```

3、_.hasIn(object, path)

检查 `path`  是否是`object` 对象的直接或继承属性。
参数
1. `object` _(Object)_: 要检索的对象。 2. `path` _(Array|string)_: 要检查的路径`path`。
返回
_(boolean)_: 如果`path`存在,那么返回 `true` ,否则返回 `false`。
例子
```plain var object = _.create({ 'a': _.create({ 'b': 2 }) });

_.hasIn(object, ‘a’);
// => true

_.hasIn(object, ‘a.b’);
// => true

_.hasIn(object, [‘a’, ‘b’]);
// => true

_.hasIn(object, ‘b’);
// => false


xfront项目中的相关使用例子如下:

```plain
 const feedback = response => {
    const type = get(response.data, 'type', 0);
    const msg = getMsg(response);
    const hasFrontMsg = hasIn(response.config, 'msg');
    switch (type) {
      case 0:
        if (hasFrontMsg) { // 此处的用处是否可以理解为判断response.config里是否包含msg属性
          Message.success(msg);
        }
        break;
      case -1:
        Message.error(msg);
        break;
      case -2:
        if (response.config.responseType !== 'blob') {
          showError({
            ...response.data,
            msg
          });
        }
        break;
    }
  };

4、`_.defaultTo(value, defaultValue)`

检查`value` ,以确定一个默认值是否应被返回。如果`value` 为`NaN` , `null` , 或者 `undefined` ,那么返回`defaultValue` 默认值。
参数
1. `value` _(*)_: 要检查的值。 2. `defaultValue` _(*)_: 默认值。
返回
_(*)_: 返回 resolved 值。
例子
```plain _.defaultTo(1, 10); // => 1

_.defaultTo(undefined, 10);
// => 10