没错,在javascript中,几乎所有东西都是对象。但是这些对象与我们在Java,C
++或其他常规语言中看到的有所不同。JS中的对象只是具有键值对的哈希表。键始终是字符串,值可以是任何东西,包括字符串,整数,布尔值,函数,其他对象等。因此,我可以创建一个新的对象,如下所示:
var obj = {}; // this is not the only way to create an object in JS并在其中添加新的键值对:
obj['message'] = 'Hello'; // you can always attach new properties to an object externally
要么
obj.message = 'Hello';
同样,如果我想向该对象添加新功能:
obj['showMessage'] = function(){ alert(this['message']);}要么
obj.showMessage = function() { alert(this.message);}现在,每当我调用此函数时,它将显示带有消息的弹出窗口:
obj.showMessage();
数组只是那些能够包含值列表的对象:
var arr = [32, 33, 34, 35]; // one way of creating arrays in JS
尽管您始终可以使用任何对象来存储值,但是使用数组可以存储它们而无需将键与每个值相关联。因此,您可以使用其索引访问项目:
alert(arr[1]); // this would show 33
数组对象与JS中的任何其他对象一样,具有其属性,例如:
alert(arr.length); // this would show 4



