对象
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 };
}
});
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
-
数据类型处理:
indexOf()
主要用于查找基本数据类型,如字符串、数字等。当使用indexOf()
查找复杂数据类型(如对象)时,它会比较内存地址,而不是深层次的内容比较。findIndex()
可以用于查找复杂数据类型,因为它允许通过回调函数来定义查找条件,这样可以进行深层次的内容比较。
-
应用场景:
indexOf()
是 ES5 中引入的数组方法,适用于查找数组中指定值的第一个索引。如果没有找到该值,则返回 -1。findIndex()
是 ES6 中引入的数组方法,它允许使用回调函数来定义查找条件,这使得findIndex()
在处理复杂数据类型时更加灵活和强大。
-
性能:
- 在某些情况下,
findIndex()
可能比indexOf()
更慢,因为它需要遍历数组并执行回调函数中的比较逻辑。但是,这种性能差异通常在大多数情况下是可以接受的,尤其是在处理复杂数据类型时。
- 在某些情况下,
-
其他方法:
- 除了
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
数组转对象
碰巧我们有一个数组,但是出于某种目的,我们需要一个具有此数据的对象,而将数组转换为对象的最快方法是使用众所周知的扩展运算符...。
let fruits = ["banana","apple","orange","watermelon"];
let fruitsObj = {...fruits};
console.log(fruitsObj)// returns {0: “banana”, 1: “apple”, 2: “orange”, 3: “watermelon”, 4: “apple”, 5: “orange”, 6: “grape”, 7: “apple”}
作者:江水流白
链接:https://www.jianshu.com/p/81e52bc80f46
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
数组去重
这里只展示两种可行的方法, 一种是使用.from()方法, 第二种是使用扩展运算符...
let fruits = ["banana","apple","orange","watermelon","apple","orange","grape","apple"]
let uniqueFruits =Array.from(new Set(fruits))
let uniqueFruits2 = [...new Set(fruits)]
合并数组
除了使用.concat()方法,我们也可以使用扩展运算符...。
varfruits = [“apple”, “banana”, “orange”];
varmeat = [“poultry”, “beef”, “fish”];
varvegetables = [“potato”, “tomato”, “cucumber”];
varfood = […fruits, …meat, …vegetables];
console.log(food);// [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]
求数组的交集
var numOne = [0,2,4,6,8,8];
var numTwo = [1,2,3,4,5,6];
var duplicatedValues = [...new Set(numOne)].filter(item=>numTwo.includes(item))
console.log(duplicatedValues);// returns [2, 4, 6]
数组对象去重
方法一:双层for循环
两两比较,如果后一个对象的id值和前一个对象的id值相等,就把后面的对象删除
let arrObj = [
{ name: "小红", id: 1 },
{ name: "小橙", id: 1 },
{ name: "小黄", id: 4 },
{ name: "小绿", id: 3 },
{ name: "小青", id: 1 },
{ name: "小蓝", id: 4 }
];
function fn1(tempArr) {
for (let i = 0; i < tempArr.length; i++) {
for (let j = i + 1; j < tempArr.length; j++) {
if (tempArr[i].id == tempArr[j].id) {
tempArr.splice(j, 1);
j--;
};
};
};
return tempArr;
};
console.log(fn1(arrObj));
方法二:indexOf()
定义一个数组存储id的值,然后逐个比较,把id值重复的对象删除即可
let arrObj = [
{ name: "小红", id: 1 },
{ name: "小橙", id: 1 },
{ name: "小黄", id: 4 },
{ name: "小绿", id: 3 },
{ name: "小青", id: 1 },
{ name: "小蓝", id: 4 }
];
function fn2(tempArr) {
let newArr = [];
for (let i = 0; i < tempArr.length; i++) {
if (newArr.indexOf(tempArr[i].id) == -1) {
newArr.push(tempArr[i].id);
} else {
tempArr.splice(i, 1);
i--;
};
};
return tempArr;
};
console.log(fn2(arrObj));
方法三:对象访问属性的方法
采用对象访问属性的方法,判断属性值是否存在
let arrObj = [
{ name: "小红", id: 1 },
{ name: "小橙", id: 1 },
{ name: "小黄", id: 4 },
{ name: "小绿", id: 3 },
{ name: "小青", id: 1 },
{ name: "小蓝", id: 4 }
];
function fn3(tempArr) {
let result = [];
let obj = {};
for (let i = 0; i < tempArr.length; i++) {
if (!obj[tempArr[i].id]) {
result.push(tempArr[i]);
obj[tempArr[i].id] = true;
};
};
return result;
};
console.log(fn3(arrObj));