Heim  >  Artikel  >  Web-Frontend  >  javascript object array方法使用详解_javascript技巧

javascript object array方法使用详解_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:47:31924Durchsuche
Array.prototype.push
push向数组尾部添加一项并更新length ,返回数组长度。
如果Object使用push会怎样?
看下面代码, obj好像数组一样工作了。length会自动更新。
复制代码 代码如下:

var push = Array.prototype.push;
var obj = {};
push.call(obj, "hello"); // 返回值 1
// obj {"0":"hello", length:0}
push.call(obj, "world"); // 返回值 2
// obj {"0":"hello", "1":"world",length:2}

Array.prototype.length Array.prototype.splice
把length和splice 给Object
看下面代码:obj这货居然变成数组了?其实不然这可能是调试工具的一些输出检查问题。
我们用 instanceof 测试 obj instanceof Array //false
var obj = { length:0, splice:Array.prototype.splice};console.log( obj ); // 打印:[]

继续看下面的代码
obj.push(0)//返回obj.length
1obj.push(1)//返回obj.length
2obj.splice(0, 1);//删除第一项 返回删除项
[0]obj.length // 1 splice删除一项的时候同样更新 length属性
这样obj的表现几乎和array一样了。不出意外slice,pop,shift,unshift什么的都可以正常工作在object中。
不过如果直接设置length,在数组中会删除大于length的下表的项, 但里的obj并不不会更新。

应用在哪?
jQuery对象表现像一个array,其实他是一个对象。这种对象如何new出来呢?
实际jQuery把Array的方法借给Object,从而达到这个jQuery对象的效果,jQuery对象内部也直接使用push等Array的方法。
看看jQuery的部分源码 (注意加粗)
复制代码 代码如下:

// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.1",
// The default length of a jQuery object is 0
length: 0,
......
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice

如果你要把Object玩成Array,那么可能潜在的问题length属性不会和“数组”项总和对应起来。
所以直接使用length设置长度不会得到支持。

看下面jquery代码,虽然length更新了,jquery的对象并没更新。(当然这并不是jquery的问题)
var jq = $('div') //假设我们在页面获取了40个
divjq.length // 40
jq.length = 0;jq// ? jq中仍然存放了40个dom对象 length属性不会和“数组”项总和对应起来。
Object使用array的方法还能正常工作,实在有些意想不到,可能实际应用远不止这些。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn