如果你是一个有经验的开发者,你可能会认为这个问题比较简单,但是有的时候,我们会感觉这个问题比较有趣。
首先我们来看看数组的定义:“An array is just a list of values which can be accessed by using an integer as the “key”. The list starts at 0 and goes up from there.”,下面我们用对象来描述数组的定义:
www.phpstudy.net\";
//Outputs: \"www.phpstudy.net\"
console.log(arr.url);
//Outputs: 2
console.log(arr.length);
下面我们来看看数组的方法,数组有很多可操作的方法,如indexOf/slice/splice/sort等,我们知道实际上这些方法存在于Array.prototype中。看下面的例子:
var arr = [\"benjamin\", \"zuojj\"];
//Outputs: 1
console.log(arr.indexOf(\"zuojj\"));
arr.indexOf = function(str) {
return \"It is customed indexOf!\";
}
//Outputs: \"It is customed indexOf!\"
console.log(arr.indexOf(\"zuojj\"));
事实上,我们可以使用对象重载所有的数组方法。看下面的push方法的例子:
var arr = {
length: 0,
push: function(val) {
//赋值
this[this.length] = val;
//更新数组长度
this.length += 1;
//返回数组长度
return this.length;
}
}
arr.push(\"zuojj\");
arr.push(\"benjamin\");
//Object {0: \"zuojj\", 1: \"benjamin\", length: 2, push: function}
console.log(arr);
但是有一个是不能从新实现的,数组的字面量定义:
var arr = [\"benjamin\", \"zuojj\"];
但是我们可以使用构造函数来代替:
var arr = new Array(\"benjamin\", \"zuojj\");
如果不适用字面量定义数组,那么我们可以重定义数组的定义,以我们自己的方式。
var myArr = new CustomArray(\"benjamin\", \"zuojj\");
现在你知道javascript中数组是如何工作的了吧,希望对大家有所帮助。