Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javaScript 对象使用和属性 #11

Open
BTFE opened this issue Jun 25, 2019 · 0 comments
Open

javaScript 对象使用和属性 #11

BTFE opened this issue Jun 25, 2019 · 0 comments

Comments

@BTFE
Copy link
Owner

BTFE commented Jun 25, 2019

JavaScript 中所有变量都可以当作对象使用,除了两个例外 nullundefined

false.toString(); // 'false'
[1, 2, 3].toString(); // '1,2,3'

function Foo(){}
Foo.bar = 1;
Foo.bar; // 1

但是数字不能当作对象使用。这是因为 JavaScript 解析器的一个错误, 它试图将点操作符解析为浮点数字面值的一部分。

12.toString() // Uncaught SyntaxError: Invalid or unexpected token

变通方法--让数字的字面值看起来像对象

12..toString(); // 第二个点号可以正常解析
12 .toString(); // 注意点号前面的空格
(12).toString(); // 12先被计算

对象访问属性两种方式

点操作符或者中括号操作符

var user = {
	name: 'provenr',
	age: 18
}
user.name //provenr
user['age'] 

两种语法是等价的,但是中括号操作符在下面两种情况下依然有效

  • 动态设置属性
  • 属性名不是一个有效的变量名 (属性名包含空格 - 或者关键词)
var user = {
	'u-name': 'provenr',
	'u age': 18
}
user['u-name'] // provenr
user['u age'] // 18

对象访问属性删除

删除属性的唯一方法是使用 delete 操作符, 只是把属性设置为undefined 或者 null 并不能真正的删除属性,仅仅只是移除了属性和值的关联

var obj = {
    bar: 1,
    foo: 2,
    baz: 3
};
obj.bar = undefined;
obj.foo = null;
delete obj.baz;

for(var i in obj) {
    if (obj.hasOwnProperty(i)) {
        console.log(i, '' + obj[i]);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant