js之Object的使用

浅拷贝:会改变原有数据
深拷贝:不会改变原有数据

  • Object.assign(obj, obj1) \(\Rightarrow\) 合并两个对象为一个==(此方法为浅拷贝)==
1
2
3
4
5
6
7
8
9
10
11
const dealObj = (val) => {
const obj = { name: "苏小妍", age: 13 };
let obj1 = { sex: "女" };
obj1 = Object.assign(obj, obj1);
// obj=====>>> { name: '苏小妍', age: 13, sex: '女' }
console.log("obj=====>>>", obj);
// obj=====>>> { name: '苏小妍', age: 13, sex: '女' }
console.log("obj1=====>>>", obj1);
};

dealObj();
这是图片
  • Object.hasOwnProperty() \(\Rightarrow\) 判断对象是否包含某个 key
1
2
3
4
5
6
7
8
9
10
11
const hasOwnPropertyObj = (val) => {
const obj = { name: "苏小妍", age: 13, sex: "女", job: "student" };
console.log("hasOwnProperty=====>>>", obj.hasOwnProperty(val));
};

// true
hasOwnPropertyObj("name");
// true
hasOwnPropertyObj("sex");
// false
hasOwnPropertyObj("work");

  • Object.keys() \(\Rightarrow\) 获取对象的所有 key
1
2
3
4
5
6
7
const objectKeys = () => {
const obj = { name: "苏小妍", age: 13, sex: "女", job: "student" };
// [ 'name', 'age', 'sex', 'job' ]
console.log("objectKeys=====>>>", Object.keys(obj));
};

objectKeys();

  • Object.values() \(\Rightarrow\) 获取对象的所有 value
1
2
3
4
5
6
const objectValues = () => {
const obj = { name: "苏小妍", age: 13, sex: "女", job: "student" };
// [ '苏小妍', 13, '女', 'student' ]
console.log("objectValues=====>>>", Object.values(obj));
};
objectValues();

  • Object.entries() \(\Rightarrow\) 获取对象的所有 key 和所有 value
1
2
3
4
5
6
7
8
9
const objectEntries = () => {
const obj = { name: "苏小妍", age: 13, sex: "女", job: "student" };
// [ 'name', '苏小妍' ],
// ['age', 13],
// ['sex', '女'],
// ['job', 'student'];
console.log("objectEntries=====>>>", Object.entries(obj));
};
objectEntries();

  • 判断数据类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const fruitsArr = [
"Banana",
"Cherry",
"Peach",
"Kiwi",
"Leamon",
"Watermelon",
"Strawberry",
"Orange",
"Apple",
"Mango",
"Banana",
];

Object.prototype.toString.call(fruitsArr.join("-")); // [object String]
Object.prototype.toString.call(fruitsArr); // [object Array]

js之Object的使用
https://www.gongyibai.site/Object/
作者
爱吃糖醋排骨的苏小妍.
发布于
2024-11-27 10:08:36
更新于
2024-12-16 16:00:28
许可协议