Accessing Javascript Array without using [] Brackets
I'm tr开发者_如何学编程ying to write some javascript in an environment where square brackets are used for macro replacement, so they can't be used as normal in the script.
If I create an array as an object with new Array()
I can use push() and pop() to access the elements, but for native arrays I can't figure out a way to get to the elements without using brackets. For example, the array returned from:
var allElements = document.getElementsByTagName("*");
Is there a way to assign a native array into an Array object so I can use push() and pop(), or is there another way to get inside?
yes, you can use prototype and slice method for example (Does not work in IE):
var index = 1;
Array.prototype.slice.call(allElements,index,index+1);
For IE, the only way I can think of is to copy all elements from collection to the array:
var newarr = new Array();
for(var i=0;i<allElements.length;i++){
newarr.push(allElements[i]);
}
Or, you can use this function (Works in IE and Firefox):
window.atIndex = function(array,index){
return eval("array" + String.fromCharCode(91) + String(index) + String.fromCharCode(93));
}
Get any item by using atIndex(allElements,0);
For NodeList
collections you can use .item()
:
var allElements = document.getElementsByTagName("*");
var firstItem = allElements.item(0);
Source: NodeList
arr = [1, 2, 3]; //just a dummy array, I assume you don't use square brackets to assign an array in your code
el0 = arr.slice(0,1).pop(); //returns 0th element
el1 = arr.slice(1,2).pop(); //returns 1st element
...
Don't have IE here, but it works fine in Firefox.
First of all, the JavaScript engine will convert literals to objects for you (it does this behind the scenes)
var arr = [1,2,3];
alert( arr.pop() );
Secondly, understand that the return value from document.getElementsByTagName()
is not an array. It's an HTMLCollection.
You could define a macro that inserts the [] braces. This might be possible. :-)
However, I am wondering why you still use this environment - even Notepad might be more comfortable then.
for loops you can iterate through the collection like
for(var item in array){
doStuff(item);
}
You could also use Jquery's makeArray function
var newArray = $.makeArray(array);
I'm assuming you have no choice in your environment square braces are a normal thing in tons of programming languages. The ideal solution is use an environment that doesn't limit your programming
精彩评论