JavaScript slice method?
I want to slice elements of one array into a new left and right array. I 开发者_StackOverflow社区am stuck on how to start this.
You'll want to start with the "slice" method. Note that it returns a NEW array without changing the old array, so you'll want to go back and mutate the old array as well.
For instance:
var a = [1,2,3,4,5],
b = a.slice(3);
a.length = 3;
// a is now [1,2,3]
// b is now [4,5]
Given this array:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
If you want to split the array so that the first 4 items go to the left array and the rest to the right array, then do this:
var leftArr = arr.slice(0, 4);
and
var rightArr = arr.slice(4);
You can make a function that returns those two arrays based on the split-position:
function splitArr(arr, i) {
return [ arr.slice(0, i), arr.slice(i) ];
}
umm..... have you looked at .slice()
?
new_array = your_array.slice( start_index , end_index );
This creates a completely new array, not a reference.
I'd use splice.
var a=[1,2,3,4,5,6];
var b=a.splice(3,a.length);
now a= [1,2,3]
and b=[4,5,6]
From http://www.w3schools.com/jsref/jsref_slice_array.asp :
Syntax :
array.slice(start, end)
Example :
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.slice(0,1) + "<br />");
document.write(fruits.slice(1) + "<br />");
document.write(fruits.slice(-2) + "<br />");
document.write(fruits);
</script>
Output :
Banana
Orange,Apple,Mango
Apple,Mango
Banana,Orange,Apple,Mango
<html>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.slice(0,1) + "<br />"); //Banana
document.write(fruits.slice(1) + "<br />"); //Orange,Apple,Mango
document.write(fruits.slice(-2) + "<br />"); //Apple,Mango
document.write(fruits); //Banana,Orange,Apple,Mango
</script>
</body>
</html>
(Reference from w3schools): http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_slice_array
精彩评论