es6 常用的object归纳总结和部分数组纠结总结

发布于:2024-04-20 ⋅ 阅读:(27) ⋅ 点赞:(0)

对象

1.Object.assign()

Object.assign() 静态方法将一个或者多个源对象中所有可枚举自有属性复制到目标对象,并返回修改后的目标对象.

1.注意target是目标对象,修改后将作为返回值,但是source不会,source是源对象

2.如果目标对象与源对象具有相同的键(属性名),则目标对象中的属性将被源对象中的属性覆盖,后面的源对象的属性将类似地覆盖前面的源对象的同名属性

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// Expected output: Object { a: 1, b: 4, c: 5 }
console.log(source);
// Expected output: Object { b: 4, c: 5 }

console.log(returnedTarget);
// Expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget === target);
// Expected output: true

3.深拷贝问题:

针对深拷贝,需要使用其他办法,因为 Object.assign() 只复制属性值。

假如源对象是一个对象的引用,它仅仅会复制其引用值。

深拷贝这样写

const copy = JSON.parse(JSON.stringify(row));

浅拷贝

 const copy = Object.assign({}, row);
  • 如果修改的是第一层(直接)属性且它们是原始类型,row 不受影响;
  • 如果修改的是第一层(直接)属性且它们是引用类型(如其他对象或数组),实际上是在修改共享的嵌套对象,此时 row 会相应地发生改变。
  • 例子如下
const row = {
  name: 'John',
  address: {
    street: 'Main St.',
    number: 123,
  },
};
 
const copy = Object.assign({}, row);
 
// 修改第一层属性(字符串),不影响 row
copy.name = 'Jane'; // row.name仍然是'John'
 
// 修改嵌套对象的属性,会影响 row
copy.address.street = 'New St.'; // row.address.street现在也是'New St.'

2.Object.create()

Object.create() 静态方法以一个现有对象作为原型,创建一个新对象

会继承父亲的对象作为一个新对象,不影响父亲

const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  },
};

const me = Object.create(person);

me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // Inherited properties can be overwritten

me.printIntroduction();
// Expected output: "My name is Matthew. Am I human? true"
console.log(me);
// Object { name: "Matthew", isHuman: true }
console.log(person);
// Object { isHuman: false, printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  } }

3.Object.keys()

Object.keys() 静态方法返回一个由给定对象自身的可枚举的字符串键属性名组成的数组。

返回的是可枚举字符串键属性名组成的数组

返回的是属性名组成的数组,如果想要属性值就是要看Object.values(),想要属性名和属性值都要就看Object.entries()

const object1 = {
  a: 'somestring',
  b: 42,
  c: false,
};

console.log(Object.keys(object1));
// Expected output: Array ["a", "b", "c"]
// 简单数组
const arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // ['0', '1', '2']

// 类数组对象
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.keys(obj)); // ['0', '1', '2']

// 键的顺序随机的类数组对象
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.keys(anObj)); // ['2', '7', '100']

// getFoo 是一个不可枚举的属性
const myObj = Object.create(
  {},
  {
    getFoo: {
      value() {
        return this.foo;
      },
    },
  },
);
myObj.foo = 1;
console.log(Object.keys(myObj)); // ['foo']

4.Object.values()

Object.values() 静态方法返回一个给定对象的自有可枚举字符串键属性值组成的数组。

const object1 = {
  a: 'somestring',
  b: 42,
  c: false,
};

console.log(Object.values(object1));
// Expected output: Array ["somestring", 42, false]
const obj = { foo: "bar", baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// 类数组对象
const arrayLikeObj1 = { 0: "a", 1: "b", 2: "c" };
console.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c']

// 具有随机键排序的类数组对象
// 使用数字键时,将按键的数字顺序返回值
const arrayLikeObj2 = { 100: "a", 2: "b", 7: "c" };
console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a']

// getFoo 是一个不可枚举的属性
const myObj = Object.create(
  {},
  {
    getFoo: {
      value() {
        return this.foo;
      },
    },
  },
);
myObj.foo = "bar";
console.log(Object.values(myObj)); // ['bar']

5.Object.enteries()

Object.entries() 静态方法返回一个数组,包含给定对象自有的可枚举字符串键属性的键值对,

每个键值对都是一个包含两个元素的数组:第一个元素是属性的键(始终是字符串),第二个元素是属性值。

const obj = { foo: "bar", baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

// 类数组对象
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]

// 具有随机键排序的类数组对象
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]

// getFoo 是一个不可枚举的属性
const myObj = Object.create(
  {},
  {
    getFoo: {
      value() {
        return this.foo;
      },
    },
  },
);
myObj.foo = "bar";
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]

6.instanceof

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car);
// Expected output: true

console.log(auto instanceof Object);
// Expected output: true

--------------------------------------------------------------------------------------

数组

1.includes()

includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

2.indexOf()

indexOf() 方法返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1

3.find

find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

  find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined 。也是要return的!这个是简单的例子,难的是看我上面map里面的那个,其实是一样,但是我以为是个值,其实确切一点说返回的是:当你的数组是大数组,里面都是小数组,假设找到userid相同的那么他返回的就是拥有第一个useid的一整项。

 this.tableData = this.tableData.map((item) => {
        const deptName = this.findLabelById(item.deptId, this.deptOptions);
        const userIds = item.userIds?.split(",");
        if (userIds) {
          const userNames = userIds
            .map((item2) => {
              const user = this.userList.find(
                (item3) => item3.userId === item2
              );
              // console.log("userNames", userNames);
              return user ? user.nickName : null;
            })
            .join(",");
          return { ...item, deptName, userNames };
        } else {
          return { ...item, deptName };
        }
      });

关于ES6数组详细解释-CSDN博客

4.findIndex()

findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// Expected output: 3

5.findindex和indexof区别

indexOf() 和 findIndex() 都是用于查找数组中满足特定条件的第一个元素的索引。它们的区别主要体现在对数据类型的处理和应用场景上。12

  1. 数据类型处理:

    • indexOf() 主要用于查找基本数据类型,如字符串、数字等。当使用 indexOf() 查找复杂数据类型(如对象)时,它会比较内存地址,而不是深层次的内容比较。
    • findIndex() 可以用于查找复杂数据类型,因为它允许通过回调函数来定义查找条件,这样可以进行深层次的内容比较。
  2. 应用场景:

    • indexOf() 是 ES5 中引入的数组方法,适用于查找数组中指定值的第一个索引。如果没有找到该值,则返回 -1。
    • findIndex() 是 ES6 中引入的数组方法,它允许使用回调函数来定义查找条件,这使得 findIndex() 在处理复杂数据类型时更加灵活和强大。
  3. 性能:

    • 在某些情况下,findIndex() 可能比 indexOf() 更慢,因为它需要遍历数组并执行回调函数中的比较逻辑。但是,这种性能差异通常在大多数情况下是可以接受的,尤其是在处理复杂数据类型时。
  4. 其他方法:

    • 除了 indexOf() 和 findIndex(),ES6 还引入了 find() 方法,它用于查找第一个符合条件的数组成员,而 filter() 方法可以用于去除重复项。

综上所述,选择使用 indexOf() 或 findIndex() 应根据数据的类型和具体的查找需求来决定。如果需要查找基本数据类型或者简单值,并且性能是一个考虑因素,indexOf() 可能是更好的选择。如果需要查找复杂数据类型或者回调函数能提供更灵活的匹配条件,那么 findIndex() 更为合适。

.Array.isArray()

console.log(Array.isArray([1, 3, 5]));
// Expected output: true

console.log(Array.isArray('[]'));
// Expected output: false

console.log(Array.isArray(new Array(5)));
// Expected output: true

console.log(Array.isArray(new Int16Array([15, 33])));
// Expected output: false

8.