程式設計雜筆

[程設雜筆] javascript Array-like vs Array

以前一直搞不懂javscript裡的Array-like和Array到底差在哪裡,今天終於有機會讓我初步了解他們的差異了。寫個……

事情發生在我要對陣列使用map function的時候


onDrop={function(data){
console.log(data);
var dataToItem=function(data,index){
console.log(data);
console.log(index);
return data.props.text;
}
self.props.updateItems(data.map(dataToItem));
}}

console結果:

[Object, Object, Object]
 Object {$$typeof: Symbol(react.element), key: "1s", ref: null, props: Object, _owner: c}
 0
 Object {$$typeof: Symbol(react.element), key: "2d", ref: null, props: Object, _owner: c}
 1
 Object {$$typeof: Symbol(react.element), key: "3d", ref: null, props: Object, _owner: c}
 2

接著,當我如法炮製,想要對以jquery .find回傳的物件做相同的時時,就發生錯誤了

 var data=$(this.getDOMNode()).find('.draggable-handle');
 var data2data2=function(data,index){
 console.log(data);
 console.log(index);
 return $(data).html();
 }
 var data2=data.map(data2data2);
console.log(data2);

問題發生在$(data).html()這行,看一下console

[div.draggable-element, context: div.draggable-element]
 0
 [div class="draggable-handle" data-reactid=".0.1.0:$reaorderable-node-1.$0asdasd.0"]asdasd[/div]
 1
 [div class="draggable-handle" data-reactid=".0.1.0:$reaorderable-node-2.$1a.0"]a[/div]
 Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined

ps: wordpress無法正常顯示<div>,以[div][/div]代替

可以發現兩者的data和index是反過來的,查了一下,才發現原因是find()回傳的是jquery類陣列(Array-like),所以有這樣的結果。要解決這樣的問題,只要

 

var data2=data.toArray().map(data2data2);

就可以了

array
Array
array-like
Array-like

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s