当前位置:网站首页>【JS】js给对象动态添加、设置、删除属性名和属性值
【JS】js给对象动态添加、设置、删除属性名和属性值
2022-08-04 05:14:00 【卸载引擎】
1. 访问对象属性
js中访问对象属性一共有两种方法:点获取法和方括号获取法。
let user = {
// 一个对象
name: "John", // 键 "name",值 "John"
age: 30, // 键 "age",值 30。列表中的最后一个属性应以逗号结尾:便于我们添加、删除和移动属性
};
- 使用点符号访问属性值
alert( user.name ); // John
- 使用方括号访问属性值
alert( user[name]); // John
注意: 如果我们遍历一个对象,我们获取属性的顺序是和属性添加时的顺序相同吗?
简短的回答是:“有特别的顺序”:整数属性会被进行排序,其他属性则按照创建的顺序显示。
2. 删除对象属性
使用delete
关键字删除对象属性
delete user.age;
delete user[age];
3. 动态设置属性
最常用的对象属性获取方法是点获取法。
但是当我们遇到需要给对象动态添加属性和属性值时,点获取法好像就不方便了,尤其是我们不知道属性名的时候更麻烦。这时候,方括号
获取法就派上用场了。
let order={
id:1,
name:'xxxx',
}
// 如果是直接给新属性赋值
order['logisticsNo']='xxxx';
// 如果添加的属性为[],则可以先创建属性值为空数组
order['logisticsNo']=[];
order['logisticsNo'].push(data); //注意数组才有push,不然会报错
// 也可以使用变量名
let key='logisticsNo';
order[key]=[];
order[key].push(data);
计算属性
当创建一个对象时,我们可以在对象字面量中使用方括号。这叫做 计算属性。
let fruit = prompt("Which fruit to buy?", "apple");
let bag = {
[fruit]: 5, // 属性名是从 fruit 变量中得到的
};
alert( bag.apple ); // 5 如果 fruit="apple"
计算属性的含义很简单:[fruit] 含义是属性名应该从 fruit 变量中获取。
所以,如果一个用户输入 “apple”,bag 将变为 {apple: 5}。
本质上,这跟下面的语法效果相同:
let fruit = prompt("Which fruit to buy?", "apple");
let bag = {
};
// 从 fruit 变量中获取值
bag[fruit] = 5;
我们可以在方括号中使用更复杂的表达式:
let fruit = 'apple';
let bag = {
[fruit + 'Computers']: 5 // bag.appleComputers = 5
};
属性存在判断: “in” 操作符
相比于其他语言,JavaScript 的对象有一个需要注意的特性:能够被访问任何属性
。即使属性不存在也不会报错!
读取不存在的属性只会得到 undefined
。所以我们可以很容易地判断一个属性是否存在:
let user = {
};
alert( user.noSuchProperty === undefined ); // true 意思是没有这个属性
in
的左边必须是 属性名。通常是一个带引号的字符串。
let user = {
name: "John", age: 30 };
alert( "age" in user ); // true,user.age 存在
alert( "blabla" in user ); // false,user.blabla 不存在。
推荐直接使用in
来判断对象的属性是否存在。
“for…in” 循环
let user = {
name: "John",
age: 30,
isAdmin: true
};
for (let key in user) {
// keys
alert( key ); // name, age, isAdmin
// 属性键的值
alert( user[key] ); // John, 30, true
}
- 检查空对象
function isEmpty(obj) {
for (let key in obj) {
// 如果进到循环里面,说明有属性。
return false;
}
return true;
}
- 对象属性求和
let salaries = {
John: 100,
Ann: 160,
Pete: 130
};
let sum = 0;
for (let key in salaries) {
sum += salaries[key];
}
alert(sum); // 390
- 将数值属性值都乘以 2
// 在调用之前
let menu = {
width: 200,
height: 300,
title: "My menu"
};
multiplyNumeric(menu);
// 调用函数之后
menu = {
width: 400,
height: 600,
title: "My menu"
};
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2;
}
}
}
边栏推荐
猜你喜欢
Get the selected content of the radio box
leetcode 12. Integer to Roman numeral
Resolved error: npm WARN config global `--global`, `--local` are deprecated
败给“MySQL”的第60天,我重振旗鼓,四面拿下蚂蚁金服offer
el-Select 选择器 底部固定
[One step in place] Jenkins installation, deployment, startup (complete tutorial)
Dynamic programming of the division of numbers
【一步到位】Jenkins的安装、部署、启动(完整教程)
The difference between px, em, and rem
应届生软件测试薪资大概多少?
随机推荐
manipulation of file contents
【流程图】
Cache pool of unity framework
8. Haproxy builds a web cluster
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.1 Arrays are not pointers
Landing, the IFC, GFC, FFC concept, layout rules, forming method, use is analysed
2023年PMP考试会用新版教材吗?回复来了!
JVM Notes
How to keep the source code confidential in the development under the burning scenario
文件系统的简单操作
DataTable uses Linq for grouping and summarization, and converts the Linq result set into DataTable
企业需要知道的5个 IAM 最佳实践
OpenGL绘制圆
[SemiDrive source code analysis] [MailBox inter-core communication] 47 - Analysis of RPMSG_IPCC_RPC mode limit size of single transmission and limit bandwidth test
redis中常见的面试题
drools from download to postman request success
QT 如何识别文件的编码格式
如何打造一篇优秀的简历
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.3 什么是声明,什么是定义
转:管理是对可能性的热爱,管理者要有闯进未知的勇气