In this tutorial we learn to make a copy/clone of an array in javascript. The traditional approach is to make another array and putting values in it by simply iterating all the elements of the subject array, whose complexity is no doubt to O(n), however javascript provide a descent solution to this problem using a method slice, slice method not only just copy/clone the entire array but is able to return a part of array as well, and most of all it is supported by all major browser including IE :)
Method signature of the said method is ...
endIndex:Optional. An integer that specifies where to end the selection. If omitted, slice() selects all elements from the start position and to the end of the array.
Method signature of the said method is ...
Array subjectArray.slice(startIndex, endIndex)startIndex:Required. An integer that specifies where to start the selection (The first element has an index of 0). You can also use negative numbers to select from the end of an array.
endIndex:Optional. An integer that specifies where to end the selection. If omitted, slice() selects all elements from the start position and to the end of the array.
Example
<script type="text/javascript"> var languages = ["JAVA", "PHP", "PYTHON", "RUBY"]; document.write(languages.slice(0,1)); document.write(languages.slice(1)); document.write(languages.slice(-2)); document.write(languages.slice(0)); </script>Output will be...
JAVA PHP,PYTHON,RUBY PYTHON,RUBY JAVA,PHP,PYTHON,RUBY
0 comments:
Post a Comment